我有%H:%M:%S:%f
格式的时间戳数据。当我阅读它并将其传递到带有pd.to_datetime的数据帧中时,除了正确传递的%H:%M:%S:%f
之外,它将自动填写01/01/1900
如何在读取数据并将其传递给时,分,秒,毫秒数据时将其设置为特定的年,月,日?
我正在使用的代码:
import pandas as pd
df = pd.DataFrame({'Time': ["00:00:00:001", "00:00:00:005","00:00:00:009"]})
df['Time'] = pd.to_datetime(df['Time'], format='%H:%M:%S:%f')
print(df)
输出:
Time
0 1900-01-01 00:00:00.001
1 1900-01-01 00:00:00.005
2 1900-01-01 00:00:00.009
所需的输出:
设置日期,例如:
Time
0 2018-11-21 00:00:00.001
1 2018-11-21 00:00:00.005
2 2018-11-21 00:00:00.009
答案 0 :(得分:3)
您可以通过多种方式进行此操作,也许最简单的方法(至少在我看来是这样)是将所需日期的字符串值附加到之后再转换为日期时间
import pandas as pd
df = pd.DataFrame({'Time': ["00:00:00:001", "00:00:00:005","00:00:00:009"]})
df["Time"] = "2018-11-21 "+ df["Time"]
df['Time'] = pd.to_datetime(df['Time'], format='%Y-%m-%d %H:%M:%S:%f')
print(df)
答案 1 :(得分:0)
df['Time']=df['Time'].apply(lambda dt: dt.replace(year=2018, day=21, month=11))