3
\$\begingroup\$

There can only be better ways to do this?

  • create strings for today's directory
  • strDate is yesterday's date in format ddmmyyyy (e.g. 08122016)
  • DateStr is yesterday's date in format yymmdd (e.g 161208)
strDate = '{d.year}{d.month:02}{d.day:02}'.format(d=datetime.datetime.now()- timedelta(1))
strDate = str(strDate)
day = calendar.day_name[datetime.datetime.today().weekday()-1]
day = day[:3]
week = datetime.datetime.today().isocalendar()[1]
fpath = strDate + "_" + str(day) + "_" + str(week) + ".zip"
DateStr = '{d.day:02}{d.month:02}{d.year}'.format(d=datetime.datetime.now()- timedelta(1))
DateStr = str(DateStr[:4]+DateStr[6:])
mdfst13
22.4k6 gold badges34 silver badges70 bronze badges
asked Dec 9, 2016 at 18:55
\$\endgroup\$
2
  • 1
    \$\begingroup\$ Can you add a description as to what this code is doing. Also some example output would be nice. \$\endgroup\$ Commented Dec 9, 2016 at 18:59
  • 1
    \$\begingroup\$ Is this code part of a program? Why are you using three different date formats? \$\endgroup\$ Commented Dec 9, 2016 at 19:09

1 Answer 1

6
\$\begingroup\$

Formatting dates

Simpler way to produce your required the formats is using the strftime symbols, for example:

# yesterday's date in format ddmmyyyy (e.g. 08122016)
strDate = '{:%d%m%Y}'.format(d - timedelta(1))
# yesterday's date in format yymmdd (e.g 161208)
DateStr = '{:%y%m%d}'.format(d - timedelta(1))

Formattings dates to use in filenames

I would strongly discourage using any of these formats in filenames. Consider adopting the yyyymmdd format instead. The good thing about this format is that the alphabetic ordering is the same as chronological ordering, which is often very practical.

String conversions

The format function of a string returns a string. So the second line here is unnecessary:

strDate = '{d.year}{d.month:02}{d.day:02}'.format(d=datetime.datetime.now()- timedelta(1))
strDate = str(strDate)

String concatenation

String concatenation like this is not recommended:

fpath = strDate + "_" + str(day) + "_" + str(week) + ".zip"

Better use the format function:

fpath = '{}_{}_{}.zip'.format(strDate, day, week)

Other Python conventions

The strDate and DateStr variable names go against the recommended naming convention. I suggest to read PEP8, it explains this and other recommendations to follow.

answered Dec 9, 2016 at 19:45
\$\endgroup\$
0

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.