简体   繁体   English

如何在 python 中将时间(对象)转换为日期时间或时间戳数据类型?

[英]How to convert Time (object) to datetime or timestamp data type in python?

Trying to convert object type variable to datetime type pd.to_datetime(df['Time'])试图将 object 类型变量转换为日期时间类型pd.to_datetime(df['Time'])

0      13:08:00
1      10:29:00
2      13:23:00
3      20:33:00
4      10:37:00

Error:<class 'datetime.time'> is not convertible to datetime错误:<class 'datetime.time'> 不能转换为 datetime

Please help how can I convert object to datetime and merge with date variable.请帮助我如何将 object 转换为日期时间并与日期变量合并。

df['col'] = df['col].astype('datetime64')

This worked for me.这对我有用。

What you have are datetime.time objects, as the error tells you.正如错误告诉您的那样,您拥有的是datetime.time对象。 You can use their string representation and parse to pandas datetime or timedelta, depending on your needs.您可以使用它们的字符串表示并解析为 pandas 日期时间或时间增量,具体取决于您的需要。 Here's three options for example,例如,这里有三个选项,

import datetime
import pandas as pd

df = pd.DataFrame({'Time': [datetime.time(13,8), datetime.time(10,29), datetime.time(13,23)]})

# 1)
# use string representation and parse to datetime:
pd.to_datetime(df['Time'].astype(str))
# 0   2022-01-19 13:08:00
# 1   2022-01-19 10:29:00
# 2   2022-01-19 13:23:00
# Name: Time, dtype: datetime64[ns]

# 2)
# add as timedelta to a certain date:
pd.Timestamp('2020-1-1') + pd.to_timedelta(df['Time'].astype(str))
# 0   2020-01-01 13:08:00
# 1   2020-01-01 10:29:00
# 2   2020-01-01 13:23:00
# Name: Time, dtype: datetime64[ns]

# 3)
# add the cumulated sum of the timedelta to a starting date:
pd.Timestamp('2020-1-1') + pd.to_timedelta(df['Time'].astype(str)).cumsum()
# 0   2020-01-01 13:08:00
# 1   2020-01-01 23:37:00
# 2   2020-01-02 13:00:00
# Name: Time, dtype: datetime64[ns]

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

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