2
rng = pd.date_range('2016-02-07', periods=7, freq='D')
print(rng[0].day)
print(rng[0].month)

7
2

I want the output with a padded zero. i.e :

07
02

a)Is there any ready function to change the format of the .day and .month?

b)Is there any other way to get day and month with padded zero ?

I have already tried the following :

rng = pd.date_range('2016-02-07', periods=7, freq='D')
r=str(rng[0])

d = datetime.strptime(r[:10], '%Y-%m-%d') #[:10] this removes time from date
z= (date.strftime(d, "%d"))
print(z)

output:

07

Thank you.

revoltman
  • 101
  • 3
  • 12

2 Answers2

4

IIUC you can use strftime:

In [8]:
rng = pd.date_range('2016-02-07', periods=7, freq='D')
days = rng.strftime('%d')
months = rng.strftime('%m')
print(days)
print(months)

['07' '08' '09' '10' '11' '12' '13']
['02' '02' '02' '02' '02' '02' '02']
EdChum
  • 376,765
  • 198
  • 813
  • 562
2

The variable rng is of Timestamp dtype:

rng[0]
Timestamp('2016-02-07 00:00:00', offset='D')

Timestamps can be formatted with a standard c-type function strftime like:

rng[0].strftime('%d')
'07'
rng[0].strftime('%m')
'02'

Please note, these are strings.

You may find additional info on formatting datetime here https://docs.python.org/3/library/datetime.html#strftime-and-strptime-behavior

Sergey Bushmanov
  • 23,310
  • 7
  • 53
  • 72