gpt4 book ai didi

python - 如何在python中转换 '22-Jul-2020 14:00 (GMT 4.30) ' "22 7 2020 "

转载 作者:行者123 更新时间:2023-12-03 19:08:50 24 4
gpt4 key购买 nike

我要转换 22-Jul-2020 14:00 (GMT 4.30)22 7 2020为了
将其插入到我的数据库中。
非常感谢您的帮助。

最佳答案

您要使用 strftime() and strptime()strptime用于将您的日期字符串更改为 datetime格式。 strftime然后将其转换回另一个格式化的字符串,假设这是您想要做的。

from datetime import datetime

s = '22-Jul-2020 14:00 (GMT 4.30)'

dt = datetime.strptime(s, '%d-%b-%Y %H:%M (%Z 4.30)')

out = dt.strftime('%d %m %Y')

print(out)
退货
22 07 2020
一个问题是 strptime将在最后格式化偏移量(GMT 4.30)的方式上挣扎。由于术语“GMT”是检索时区所需的全部内容,我建议使用 regex 去除其余部分- 如果时区对您很重要。
import re
from datetime import datetime

s = '22-Jul-2020 14:00 (GMT 4.30)'

s_stripped = re.sub('\(([A-Z]+).+\)', r'\1', s)
# s_stripped is '22-Jul-2020 14:00 GMT'

dt = datetime.strptime(s_stripped, '%d-%b-%Y %H:%M %Z')

out = dt.strftime('%d %m %Y')

print(out)

关于python - 如何在python中转换 '22-Jul-2020 14:00 (GMT 4.30) ' "22 7 2020 ",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62907595/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com