Python:如何将UTC时间戳从mm/dd/yyyy hh:mm:ss AM更改为dd/mm/yyyy hh:mm:ss AM [英] Python: How can I change a UTC timestamp from mm/dd/yyyy hh:mm:ss AM to dd/mm/yyyy hh:mm:ss AM

查看:52
本文介绍了Python:如何将UTC时间戳从mm/dd/yyyy hh:mm:ss AM更改为dd/mm/yyyy hh:mm:ss AM的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我似乎无法在python中更改UTC时间戳格式.日期采用以下格式(它们在Excel工作表中)

I cant seem to change a UTC timestamp format in python. The dates are in the following format (They are in an excel sheet)

UTC事件时间戳

1/22/2021 8:45:28 AM

1/22/2021 8:45:28 AM

1/22/2021 8:47:52 AM

1/22/2021 8:47:52 AM

我正在尝试使用以下代码,但一直说格式不匹配

I am trying to use the following piece of code but it keeps saying that the format doesn't match

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)

推荐答案

您可以直接使用

You can directly use pandas.to_datetime on your dataframe:

>>> 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 例如:

Your problem isn't the format, it is str(col). To convert a column to string you call pandas.Series.astype, if you call str it no longer remains a Series or df, for example:

>>> 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 .

您的代码适用于单个值:

Your code works for a single value:

>>> 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'

如果要使用非前导零填充格式,请使用:

If you want non leading zero-padded format, use:

# 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'

这篇关于Python:如何将UTC时间戳从mm/dd/yyyy hh:mm:ss AM更改为dd/mm/yyyy hh:mm:ss AM的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆