简体   繁体   English

pd.read_csv-纪元日期转换

[英]pd.read_csv - epoch date conversion

I have csv with date columns, Bill Date for example, stored as the Excel serial number for the date. 我有带日期列的csv,例如“ Bill Date ”,存储为该日期的Excel序列号。 So 12/15/2017 is represented in the csv as 43084. I need to convert this in my DataFrame to an actual date Pandas / Python recognizes. 因此12/15/2017在csv中表示为43084。我需要在DataFrame中将其转换为Pandas / Python可以识别的实际日期。 So, my question: Is there a more efficient method than what I've used to convert the dates? 因此,我的问题是:是否有比我转换日期更有效的方法?

df:
    Bill Date
0       43084

Excel stores dates as days since Jan 1, 1900 and pandas defaults to Jan 1, 1970. Excel将日期存储为自1900年1月1日以来的天数,而熊猫默认为1970年1月1日。

diff = pd.Timestamp('1970-01-01') - pd.Timestamp('1900-01-01')
pd.to_datetime([43084 - (diff.days + 2)], unit='d')

DatetimeIndex(['2017-12-15'], dtype='datetime64[ns]', freq=None)

So, am I missing something obvious here (eg, an option for a different origin)? 那么,我在这里是否缺少明显的东西(例如,其他来源的选项)?

Just do this: 只要这样做:

 import pandas as pd
 from datetime import datetime

 df = pd.read_csv("yourdataframe.csv")
 df["Bill_Date"] = df["Bill_Date"].map(lambda x: datetime.fromordinal(datetime(1900, 1, 1).toordinal() + x - 2))
 df["Bill_Date"] = df["Bill_Date"].map(lambda x: x.strftime("%Y-%m-%d"))

 print df.head()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM