-2

I would like to take a date range in python, than create a new series/column the has the date formatted as a string as YYYYMMDD

This is what I have so far:

start = '20200214' # YYYYMMDD
end = '20200216' # YYYYMMDD

dates = pd.DataFrame(pd.to_datetime(pd.date_range(start,end).date),columns = ['dates'])
dates['Year'] = dates['dates'].dt.year
dates['Month'] = dates['dates'].dt.month
dates['Day'] = dates['dates'].dt.day

I tried to add each element as a string, dates.Year.astype(str) + dates.Month.astype(str)+..., but I need leading zeros.

So take the first date, 2020-02-14 and change it to 20200214. Then rinse and repeat for all others.

martineau
  • 119,623
  • 25
  • 170
  • 301
Jack Armstrong
  • 1,182
  • 4
  • 26
  • 59
  • Does this answer your question? [datetime to string with series in python pandas](https://stackoverflow.com/questions/30132282/datetime-to-string-with-series-in-python-pandas) – AMC Feb 11 '20 at 19:25
  • Have you done any research? There are plenty of resources on the subject, including the one above. – AMC Feb 11 '20 at 19:25

5 Answers5

1

Your solution is possible with Series.str.zfill:

dates['Year'] = dates['dates'].dt.year
dates['Month'] = dates['dates'].dt.month
dates['Day'] = dates['dates'].dt.day
dates['dates1'] = (dates.Year.astype(str).str.zfill(2) + 
                   dates.Month.astype(str).str.zfill(2) + 
                   dates['Day'].astype(str))

But simplier and faster is use Series.dt.strftime:

dates['dates2'] = dates['dates'].dt.strftime('%Y%m%d')

print (dates)
       dates  Year  Month  Day    dates1    dates2
0 2020-02-14  2020      2   14  20200214  20200214
1 2020-02-15  2020      2   15  20200215  20200215
2 2020-02-16  2020      2   16  20200216  20200216
jezrael
  • 822,522
  • 95
  • 1,334
  • 1,252
1
dates['reformatted_date'] = dates['dates'].dt.strftime('%Y%m%d')

Output:

       dates  Year  Month  Day reformatted_date
0 2020-02-14  2020      2   14         20200214
1 2020-02-15  2020      2   15         20200215
2 2020-02-16  2020      2   16         20200216
Yuna A.
  • 149
  • 6
0
>>> "{:02d}".format(1)
'01'
>>> "{:02d}".format(12)
'12'
ishefi
  • 480
  • 4
  • 12
0

Using np.where checking for the condition whether it is less than 10 and adding the 0 or not:

dates['final'] = dates['Year'].astype(str) + np.where(dates['Month'] < 10,"0"+dates['Month'].astype(str),dates['Month'].astype(str))+ np.where(dates['Day'] < 10,"0"+dates['Day'].astype(str),dates['Day'].astype(str))
Celius Stingher
  • 17,835
  • 6
  • 23
  • 53
0

Also this option:

d = datetime.datetime.now()
c = str(d)[0:10] //to string
print(c.replace('-', '')) 
//data comes in this format yyyy-mm-dd hh:mm:ss
//output yyyymmdd

or this:

d = datetime.datetime.now()
c = d.isoformat() //to string
e = c[0:10]
print (e.replace('-', ''))
//data comes in this format yyyy-mm-dd hh:mm:ss
//output yyyymmdd
Dichado
  • 37
  • 10