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:])
  • 1
    \$\begingroup\$ Can you add a description as to what this code is doing. Also some example output would be nice. \$\endgroup\$
    – Peilonrayz
    Dec 9, 2016 at 18:59
  • 1
    \$\begingroup\$ Is this code part of a program? Why are you using three different date formats? \$\endgroup\$ Dec 9, 2016 at 19:09

1 Answer 1


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.


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.