0
from datetime import date
today = dt.datetime.today().date()

todays_file = 'C:\\Temp\\'+str(today.year)+str(today.month)+str(today.day)+str('.csv')

Running:

todays_file

gives:

'C:\\Temp\\2018124.csv'

BUT - I need this to be in the format yyyymmdd (not yyyymmd)

So expected output is:

'C:\\Temp\\20181204.csv'

Similarly, expected output on 3rd feb 2019 is:

'C:\\Temp\\20190203.csv'

Is there a smart way without using if len(today.day or today.month) = 1: etc

num3ri
  • 822
  • 16
  • 20
Junaid Mohammad
  • 457
  • 1
  • 6
  • 18

3 Answers3

1

You can do that:

d = datetime.datetime.now()
todays_file = 'C:\\Temp\\' + str(d.year) + str("%02d"%d.month) + str("%02d"%d.day) + '.csv'

Give:

'C:\\Temp\\20181204.csv'
B.Gees
  • 1,125
  • 2
  • 11
  • 28
0

Use .strftime("%Y%m%d")

Ex:

import datetime
today = datetime.datetime.today().date()

todays_file = r'C:\\Temp\\{}.csv'.format(today.strftime("%Y%m%d"))    
print(todays_file)

Output:

C:\\Temp\\20181204.csv

You can also use str.format or fstring to form your required result string.

Rakesh
  • 81,458
  • 17
  • 76
  • 113
0
from datetime import date
today_str = date.today().strftime('%Y%m%d')
file_name = '{}.csv'.format(today_str)
# or in python 3.6+
file_name = f'{today_str}.csv'
buran
  • 13,682
  • 10
  • 36
  • 61