如何在 pandas 中阅读 AM/PM 次?
How to read AM/PM times in pandas?
我正在处理一个 csv 文件,其中包含名为 startTime 的列,其中包含时间。
使用 Excel 打开此文件时,公式栏中的时间显示为 AM/PM 次,尽管列中的时间戳格式不正确:
startTime
16:02.0
17:45.0
18:57.0
20:23.0
使用 pandas' read_csv
读取此文件时,我无法正确设置这些时间戳的格式:
import pandas as pd
df = pd.read_csv('example_file.csv')
print(df.startTime)
简单地产生:
0 16:02.0
1 17:45.0
2 18:57.0
3 20:23.0
我首先尝试使用 pd.to_datetime(df.startTime,format=" %H%M%S")
转换输出系列,但这会产生以下错误消息:
time data '16:02.0' does not match format ' %H%M%S' (match)
然后我根据 this answer 尝试了 pd.to_datetime(df.startTime,format=" %I:%M:%S %p")
,以考虑 AM/PM 约定,但这返回了相同的错误消息。
如何使用 pandas 像 Excel 一样自动格式化这些时间戳?
尝试:
>>> pd.to_datetime(df['startTime'].str.strip(), format='%H:%M.%S')
0 1900-01-01 16:02:00
1 1900-01-01 17:45:00
2 1900-01-01 18:57:00
3 1900-01-01 20:23:00
Name: startTime, dtype: datetime64[ns]
你的csv文件有文本,没有datetime,所以你需要先把这个列中存储的文本转换成pandasdatetime对象,然后你可以把这个pandasdatetime对象转换成通过 strftime
方法所需的格式:
pd.to_datetime(df['startTime']).dt.strftime(date_format = '%I:%M:%S %p')
输出:
0 04:02:00 PM
1 05:45:00 PM
2 06:57:00 PM
3 08:23:00 PM
注意:这些值是字符串值,不是日期时间。
针对此特定问题进行编辑:
在转换为午夜 AM 之前将 00h 添加到时间戳的快速格式:
pd.to_datetime(df['startTime'].apply(lambda x: f'00:{x}')).dt.strftime(date_format = '%I:%M:%S %p')
输出:
0 00:16:02 AM
1 00:17:45 AM
2 00:18:57 AM
3 00:20:23 AM
强制转换为 datetetime 并使用 dt.strftime
提取时间
df['startTime']=pd.to_datetime(df['startTime']).dt.strftime('%I:%M.%S%p')
我正在处理一个 csv 文件,其中包含名为 startTime 的列,其中包含时间。
使用 Excel 打开此文件时,公式栏中的时间显示为 AM/PM 次,尽管列中的时间戳格式不正确:
startTime
16:02.0
17:45.0
18:57.0
20:23.0
使用 pandas' read_csv
读取此文件时,我无法正确设置这些时间戳的格式:
import pandas as pd
df = pd.read_csv('example_file.csv')
print(df.startTime)
简单地产生:
0 16:02.0
1 17:45.0
2 18:57.0
3 20:23.0
我首先尝试使用 pd.to_datetime(df.startTime,format=" %H%M%S")
转换输出系列,但这会产生以下错误消息:
time data '16:02.0' does not match format ' %H%M%S' (match)
然后我根据 this answer 尝试了 pd.to_datetime(df.startTime,format=" %I:%M:%S %p")
,以考虑 AM/PM 约定,但这返回了相同的错误消息。
如何使用 pandas 像 Excel 一样自动格式化这些时间戳?
尝试:
>>> pd.to_datetime(df['startTime'].str.strip(), format='%H:%M.%S')
0 1900-01-01 16:02:00
1 1900-01-01 17:45:00
2 1900-01-01 18:57:00
3 1900-01-01 20:23:00
Name: startTime, dtype: datetime64[ns]
你的csv文件有文本,没有datetime,所以你需要先把这个列中存储的文本转换成pandasdatetime对象,然后你可以把这个pandasdatetime对象转换成通过 strftime
方法所需的格式:
pd.to_datetime(df['startTime']).dt.strftime(date_format = '%I:%M:%S %p')
输出:
0 04:02:00 PM
1 05:45:00 PM
2 06:57:00 PM
3 08:23:00 PM
注意:这些值是字符串值,不是日期时间。
针对此特定问题进行编辑:
在转换为午夜 AM 之前将 00h 添加到时间戳的快速格式:
pd.to_datetime(df['startTime'].apply(lambda x: f'00:{x}')).dt.strftime(date_format = '%I:%M:%S %p')
输出:
0 00:16:02 AM
1 00:17:45 AM
2 00:18:57 AM
3 00:20:23 AM
强制转换为 datetetime 并使用 dt.strftime
提取时间df['startTime']=pd.to_datetime(df['startTime']).dt.strftime('%I:%M.%S%p')