在python中将YYY-M-D HH:MI:SS转换为可读字符串



我有像2021-05-03 14:51:56.769715一样的时间。我需要转换成可读字符串python中的May 3, 2021, 2:51:56 PM。我需要通过时区同时转换它。

有什么方法可以在python中做到这一点吗?

提前感谢:(

这应该符合您想要的格式:

from datetime import datetime
# Original string
str_date = '2021-05-03 14:51:56.769715'
# Datetime object creation from original string
obj_date = datetime.strptime(str_date, '%Y-%m-%d %H:%M:%S.%f')
# Result string with the desired format
converted_str = datetime.strftime(obj_date, '%b %-d, %Y, %-I:%-M:%-S %p')
# Print the result
print(converted_str)

上面的代码将打印May 3, 2021, 2:51:56 PM,正如您所期望的那样。然而,我猜您不希望使用零填充的分钟和秒,但如果您愿意,则应该使用%M%S,而不是%-M%-S

有关Python中日期格式的更多信息,您应该查看Python strftime参考

最新更新