0

file.write("%s," %(fake.date_between(start_date=datetime(2001,1,1),end_date= datetime(2015,1,1))).strftime("%m / %Y").replace('0 ',' '))

While writing data into csv file I want the output as monthnumber/year ex 8/2019 but this code returns Aug-2019 when I check in the csv file. What is the error?

Nishanthi
  • 1
  • 2

1 Answers1

1

"Aug-2019" can result from using "%b-%Y", not from "%m / %Y". Please double check with this doc: https://docs.python.org/2/library/datetime.html#strftime-strptime-behavior

Since you need output like "8/2019", obvious choice for the year part is to use "%Y". But it's a little tricky for the month part, since python only allows zero padded numeric month output i.e. the "%m". The leading zero will occur for some months, but not all. A straight forward replace will not work here. I suggest using regex. The snippet below shows how regex can be used for removing the leading zero, if any.

import re
import datetime
d = datetime.datetime.now()
d.strftime('%m/%Y') # --> '03/2020'
re.sub('^0', '', d.strftime('%m/%Y')) # --> '3/2020'
Raiyan
  • 1,589
  • 1
  • 14
  • 28
  • the leading zero can be replaced by replace function file.write("%s," %(fake.date_between(start_date=datetime(2001,1,1),end_date= datetime(2015,1,1))).strftime("%m / %Y").replace('0 ',' ')) – Nishanthi Mar 27 '20 at 13:47
  • I must be misunderstanding something here. `"%m / %Y"` should give you a string like "03 / 2020". Then doing `replace('0 ', '')` should not make any difference because the substring "0 " does not occur in "03 / 2020". For clarity, what is the output of `fake.date_between(start_date=datetime(2001,1,1),end_date= datetime(2015,1,1)))` ? – Raiyan Mar 27 '20 at 13:58