我似乎无法在 python 中更改 UTC 时间戳格式。 日期格式如下(在excel表中)
UTC 事件时间戳
2021/1/22 上午 8:45:28
2021/1/22 上午 8:47:52
我正在尝试使用以下代码,但它一直说格式不匹配
string_col = str(df[' UTC Event Timestamp'])
string_col.strip()
t = datetime.strptime(string_col, '%m/%d/%Y %I:%M:%S %p')
dt_to_string = t.strftime('%d/%m%Y %I:%M:%S %p')
print(dt_to_string)
答案 0 :(得分:0)
您可以直接在数据框上使用 pandas.to_datetime
:
>>> s = pd.Series(["1/22/2021 8:45:28 AM", "1/22/2021 8:47:52 AM"])
>>> s
0 1/22/2021 8:45:28 AM
1 1/22/2021 8:47:52 AM
dtype: object
>>> t = pd.to_datetime(s, format='%m/%d/%Y %I:%M:%S %p')
>>> t
0 2021-01-22 08:45:28
1 2021-01-22 08:47:52
dtype: datetime64[ns]
>>> t.dt.strftime('%d/%m/%Y %I:%M:%S %p')
0 22/01/2021 08:45:28 AM
1 22/01/2021 08:47:52 AM
dtype: object
您的问题不是格式,而是str(col)
。要将列转换为字符串,您调用 pandas.Series.astype
,如果您调用 str
,它不再保持为 Series
或 df
,例如:
>>> s
0 1/22/2021 8:45:28 AM
1 1/22/2021 8:47:52 AM
dtype: object
>>> str(s)
'0 1/22/2021 8:45:28 AM\n1 1/22/2021 8:47:52 AM\ndtype: object'
^ 这不适用于 datetime.datetime.strptime
。
您的代码适用于单个值:
>>> s
0 1/22/2021 8:45:28 AM
1 1/22/2021 8:47:52 AM
>>> s[0]
'1/22/2021 8:45:28 AM'
>>> datetime.strptime(s[0], '%m/%d/%Y %I:%M:%S %p')
datetime.datetime(2021, 1, 22, 8, 45, 28)
>>> datetime.strptime(s[0], '%m/%d/%Y %I:%M:%S %p').strftime('%d/%m/%Y %I:%M:%S %p')
'22/01/2021 08:45:28 AM'
如果您想要非前导零填充格式,请使用:
# On Windows (use '%#m' instead of '%m')
>>> datetime.strptime(s[0], '%m/%d/%Y %I:%M:%S %p').strftime('%d/%#m/%Y %I:%M:%S %p')
'22/1/2021 08:45:28 AM'
# On Linux (use '%-m' instead of '%m')
>>> datetime.strptime(s, '%m/%d/%Y %I:%M:%S %p').strftime('%d/%-m/%Y %I:%M:%S %p')
'22/1/2021 08:45:28 AM'