在python中将YY-M-D HH:MI:SS转换为可读字符串
我的时间是2021-05-0314:51:56.769715。我需要转换成可读的字符串,比如在python中将YY-M-D HH:MI:SS转换为可读字符串,python,python-3.x,datetime,Python,Python 3.x,Datetime,我的时间是2021-05-0314:51:56.769715。我需要转换成可读的字符串,比如 2021年5月3日下午2:51:56用python编写。在转换时区时,我还需要传递时区 有什么方法可以用python实现吗 提前感谢:)这应该符合您想要的格式: from datetime import datetime # Original string str_date = '2021-05-03 14:51:56.769715' # Datetime object creation from
2021年5月3日下午2:51:56用python编写。在转换时区时,我还需要传递时区
有什么方法可以用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)
正如您所期望的那样,上面的代码将在2021年5月3日下午2:51:56打印。但是,我猜您不希望使用零填充分和秒,但是如果您愿意,您应该使用%M
和%S
而不是%-M
和%-S
有关Python中日期格式的详细信息,您应该检查正在查找的datetime.strftime()
和strftime()
来解析原始字符串。datetime.fromsoformat(“2021-05-03 14:51:56.769715”).strftime(%B%d,%Y,%I:%M:%S%p”)
?有关更多格式化/解析指令,请参阅。相关:,是否有方法传递时区?感谢您的回复。我尝试使用strftime(“%b%d,%Y,%-I:%M:%-S%p”)。是否有方法传递时区?可以使用%z(表示时区的数字偏移量)或%z(表示时区缩写)