我是熊猫的新手,当我运行下面的代码时,我得到了不同的结果:
import pandas as pd
ts = pd.to_datetime("2014-6-10 10:10:10.30",format="%Y-%m-%d %H:%M:%S.%f")
print ts
ts = pd.to_datetime("6-10 10:10:10.30",format="%m-%d %H:%M:%S.%f")
print ts
Run Code Online (Sandbox Code Playgroud)
输出是:
2014-06-10 10:10:10.300000
1900-06-10 10:10:10.300000
Run Code Online (Sandbox Code Playgroud)
这意味着默认年份是 1900 年,如何将其更改为 2014 年的第二年?
您不能写入year
日期时间的属性,因此最简单的方法是使用replace
:
In [57]:
ts = ts.replace(year=2014)
ts
Out[57]:
Timestamp('2014-06-10 10:10:10.300000')
Run Code Online (Sandbox Code Playgroud)
另一种可能性是将当前年份存储为字符串并根据需要添加它,这样的优点是您可以对所有日期使用相同的格式字符串:
In [68]:
this_year = str(datetime.datetime.now().year)
datestr = this_year +'-' + '6-10 10:10:10.30'
pd.to_datetime(datestr,format="%Y-%m-%d %H:%M:%S.%f")
Out[68]:
Timestamp('2014-06-10 10:10:10.300000')
Run Code Online (Sandbox Code Playgroud)
想不出更好的方法,但您可以将上述内容包装在一个函数中以测试是否需要设置年份
归档时间: |
|
查看次数: |
1370 次 |
最近记录: |