Python:如何将UTC时间戳从mm/dd/yyyy hh:mm:ss AM更改为dd/mm/yyyy hh:mm:s



我似乎无法在python中更改UTC时间戳格式。日期格式如下(在excel表格中)

UTC EVENT TIMESTAMP

1/22/2021 8:45:28 AM

1/22/2021 8:47:52 AM

我试图使用下面的代码,但它一直说格式不匹配

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)

你可以直接在你的数据框架上使用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,则不再保留Seriesdf,例如:

>>> 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 AMn1    1/22/2021 8:47:52 AMndtype: 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'

最新更新