I want to change the following format
2012-12-22
2012-12-24
2012-12-25
to the excel style format
44120
44121
44123
How can I convert the DateTime format to excel style in pandas?
I want to change the following format
2012-12-22
2012-12-24
2012-12-25
to the excel style format
44120
44121
44123
How can I convert the DateTime format to excel style in pandas?
You can write your own converter, pure Python example:
from datetime import datetime, timezone
def toExcelSerialDate(dt, _origin=datetime(1899,12,30,tzinfo=timezone.utc)):
"""
convert a datetime object to Excel serial date
"""
return (dt-_origin).total_seconds()/86400 # output in days since origin
for s in ["2012-12-22", "2012-12-24", "2012-12-25"]:
print(toExcelSerialDate(datetime.fromisoformat(s).replace(tzinfo=timezone.utc)))
# 41265.0
# 41267.0
# 41268.0
applied to a pandas df:
import pandas as pd
df = pd.DataFrame({'datetime': ["2012-12-22", "2012-12-24", "2012-12-25"]})
# make sure your column is of dtype datetime:
df['datetime'] = pd.to_datetime(df['datetime'])
# subtract origin and convert to days:
df['excelDate'] = (df['datetime']-pd.Timestamp("1899-12-30")).dt.total_seconds()/86400
# df['excelDate']
# 0 41265.0
# 1 41267.0
# 2 41268.0
# Name: excelDate, dtype: float64