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

Tal*_*abi 5 python date-format python-3.x

我想转换22-Jul-2020 14:00 (GMT 4.30)22 7 2020以便将其插入到我的数据库中。

非常感谢您的帮助。

ric*_*ton 4

您想使用strftime() 和 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)
Run Code Online (Sandbox Code Playgroud)

退货

22 07 2020
Run Code Online (Sandbox Code Playgroud)

一个问题是strptime最终的偏移量 (GMT 4.30) 的格式化方式会很困难。由于术语“GMT”是检索时区所需的全部内容,因此我建议使用正则表达式删除其余部分- 如果时区对您很重要。

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)
Run Code Online (Sandbox Code Playgroud)