我有一个像 datetime
这样的 2020/10/26 7:56:35 午後 GMT+9
字符串,我想将该字符串更改为 datetime
格式。
目前我正在使用 strptime()
方法,格式文本为 %Y-%m%d %I%M%S %p GMT 9
但这是错误的。在 datetime
字符串中包含日语可以吗?
答案 0 :(得分:4)
去掉一些已发表的评论,您可以使用 .replace
将 AM 和 PM 更改为英文。
from datetime import datetime
theTime="2020/10/26 7:56:35 午後 GMT+9"
theTime = theTime.replace("午後", "PM").replace("午前", "AM")
dateTime = datetime.strptime(theTime, "%Y/%m/%d %I:%M:%S %p GMT+9")
print(dateTime)
输出:
2020-10-26 19:56:35
答案 1 :(得分:1)
dateparser 在这里做得很好:
import dateparser # pip install dateparser
# AM:
dateparser.parse("2020/10/26 7:56:35 午前 GMT+9")
Out[4]: datetime.datetime(2020, 10, 26, 7, 56, 35, tzinfo=<StaticTzInfo 'UTC\+09:00'>)
# PM:
dateparser.parse("2020/10/26 7:56:35 午後 GMT+9")
Out[5]: datetime.datetime(2020, 10, 26, 19, 56, 35, tzinfo=<StaticTzInfo 'UTC\+09:00'>)
答案 2 :(得分:1)
这里只是一个快速的游戏。您可以使用我创建的 dictionary
'jap_eng' 来转换/填充 PM
和 AM
格式。
from datetime import datetime
datetime_str = '2020/10/26 7:56:35 午後 GMT+9'
jap_eng = {'午後':'PM', '午前': 'AM'}
full_dt_str = datetime_str[:-8] + jap_eng[datetime_str[-8:-6]]
datetime_object = datetime.strptime(full_dt_str, '%Y/%m/%d %H:%M:%S %p')
这将输出:
datetime.datetime(2020, 10, 26, 7, 56, 35)
答案 3 :(得分:1)
“pythonic”是在不使用第三方模块的情况下完成的,看起来像这样。
from datetime import datetime
time1="2020/10/26 7:56:35 午後 GMT+9"
#time1="2020/10/26 7:56:35 午前 GMT+9"
#time1="2020/10/26 7:56:35 FM GMT+9"
try:
parsed_time = datetime.strptime(time1, "%Y/%m/%d %I:%M:%S %p GMT+9")
except ValueError:
time1PM = time1.replace("午後", "PM")
try:
parsed_time = datetime.strptime(time1PM, "%Y/%m/%d %I:%M:%S %p GMT+9")
except ValueError:
time1AM = time1.replace("午前", "AM")
parsed_time = datetime.strptime(time1AM, "%Y/%m/%d %I:%M:%S %p GMT+9")
print(parsed_time)
另一种替代方法是使用正则表达式将日语指定替换为等效的子字符串 strptime()
理解:
from datetime import datetime
import re
def multiple_replace(mdict, text):
''' Replace keys that match with their corresponding value in dictionary. '''
regex = re.compile("(%s)" % "|".join(map(re.escape, mdict.keys())))
return regex.sub(lambda mo: mdict[mo.string[mo.start():mo.end()]], text)
time_str="2020/10/26 7:56:35 午後 GMT+9"
#time_str="2020/10/26 7:56:35 午前 GMT+9"
#time_str="2020/10/26 7:56:35 FM GMT+9"
AMPM = {"午後": "PM", "午前": "AM"}
parsed_time = datetime.strptime(multiple_replace(AMPM, time_str),
"%Y/%m/%d %I:%M:%S %p GMT+9")
print(parsed_time)