在 Pandas 中转换日期/时间
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11918342/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Converting date/time in Pandas
提问by vgoklani
I have stock ticker data in the following format:
我有以下格式的股票代码数据:
40289.65972
40289.66319
40289.66667
and Excel is able to magicallyconvert them to:
Excel 能够神奇地将它们转换为:
4/22/14 3:50 PM
4/22/14 3:55 PM
4/22/14 4:00 PM
via "Format Cells"
通过“格式化单元格”
How do I do the same conversion in pandas?
我如何在 中进行相同的转换pandas?
回答by vgoklani
The solution mentioned in the link above works, so I will just repost the snippet here. Thanks!
上面链接中提到的解决方案有效,因此我将在此处重新发布代码段。谢谢!
import datetime
def minimalist_xldate_as_datetime(xldate, datemode):
# datemode: 0 for 1900-based, 1 for 1904-based
return (
datetime.datetime(1899, 12, 30)
+ datetime.timedelta(days=xldate + 1462 * datemode)
)
回答by jdmarino
To stay within pandas (which is wicked fast), use to_timedelta()
为了留在熊猫(这是邪恶的快),使用 to_timedelta()
import pandas as pd
# should get 7/7/1988 1:26:24 a.m. (https://support.microsoft.com/en-us/kb/214094)
pd.to_datetime('1899-12-30') + pd.to_timedelta(32331.06, 'D')
produces
Timestamp('1988-07-07 01:26:24')If you have a dataframe full of excel-float-dates you can convert the whole thing:
生产
Timestamp('1988-07-07 01:26:24')如果你有一个数据帧完整的Excel的浮动日期,你可以将整个事情:
df['BetterDT'] = pd.to_datetime('1899-12-30') + pd.to_timedelta(df.ExecDate, 'D')
回答by Alejandro
Excel considers 1900 a leap year, so be careful with exactly what you want to translate: http://spreadsheetpage.com/index.php/oddity/the_intentional_date_bug/
Excel 认为 1900 年是闰年,所以要小心你想要翻译的内容:http: //spreadsheetpage.com/index.php/oddity/the_intentional_date_bug/

