2

I have a Pandas Dataframe with 2000+ rows with date in float format as below:

42704.99686342593 representing datetime value of (2016, 11, 30, 23, 55, 29)

What I want to do is iterate each row in the dataframe and convert the float to the correct datetime format ideally d/m/Y H/M/S and save this to a new dataframe.

Using Python 2.7.

I couldn't find any duplicate questions and was unable to solve the issue with solutions to similar questions so any help appreciated.

Thanks.

Mohammad Yusuf
  • 16,554
  • 10
  • 50
  • 78
GoodCat
  • 117
  • 2
  • 9

1 Answers1

3

It seems you use serial date what is Excel format.

The simpliest is substract 25569 and use to_datetime with parameter unit='d':

df =  pd.DataFrame({'date':[42704.99686342593,42704.99686342593]})
print (df)
           date
0  42704.996863
1  42704.996863

print (pd.to_datetime(df.date - 25569, unit='d'))

0   2016-11-30 23:55:28.963200
1   2016-11-30 23:55:28.963200
Name: date, dtype: datetime64[ns]

Another solutions are substract timedelta or offset:

print (pd.to_datetime(df.date, unit='d') - pd.to_timedelta('25569 Days'))
0   2016-11-30 23:55:28.963200
1   2016-11-30 23:55:28.963200
Name: date, dtype: datetime64[ns]

print (pd.to_datetime(df.date, unit='d') - pd.offsets.Day(25569))
0   2016-11-30 23:55:28.963200
1   2016-11-30 23:55:28.963200
Name: date, dtype: datetime64[ns]

Thank you Ted Petrou for link.

Community
  • 1
  • 1
jezrael
  • 822,522
  • 95
  • 1,334
  • 1,252