可以在毫秒级时间戳上使用pd.datetime()吗?

时间:2019-02-18 20:15:42

标签: python pandas milliseconds

我正在尝试将对象的时间(从csv文件中读取)转换为日期时间格式。 我的时间格式是07:00:00.16(小时:分钟:seconds.milliseconds)

import pandas as pd 
df=pd.read_csv('Copy.txt')
df.columns = df.columns.str.strip()
df['Time']=pd.to_datetime(df.Time, errors = 'coerce')

我的结果是“时间”列全为“ NaT”

如果我使用:df['Time']=pd.to_datetime(df.Time)

比我得到这个错误:OutOfBoundsDatetime: Out of bounds nanosecond timestamp: 1-01-01 07:00:00

请建议如何更改列类型并保留完整的毫秒数据。 谢谢!

数据格式为:

0       07:00:00.0
1       07:00:00.1
2       07:00:00.2
3       07:00:00.3
4       07:00:00.4
5       07:00:00.5
6       07:00:00.6
7       07:00:00.7
8       07:00:00.8
9       07:00:00.9
10     07:00:00.10
11     07:00:00.11
12     07:00:00.12
13     07:00:00.13
14     07:00:00.14
15     07:00:00.15
16     07:00:00.16
Name: Time, dtype: object

1 个答案:

答案 0 :(得分:1)

如果您的csv具有以'07:00:00.16'之类的字符串格式存储的时间,则只需指定格式并提取time部分,即可将您的列转换为datetime对象:

df['Time'] = pd.to_datetime(df['Time'], format='%H:%M:%S.%f').dt.time