这是我的代码:
from datetime import datetime
def get_local_time(time_str):
"""
takes a string in the format of '27 March at 3:00' which is UTC
and converts it to local time and AM/PM
:param time_str:
"""
offset = datetime.now() - datetime.utcnow()
time_dt = datetime.strptime(time_str, '%d %b at %H:%M')
return (time_dt + offset).strftime('%I:%M %p')
我遇到的问题是使用 time_str,它只是时间,不包括日/月。即:“02:00”
如果我将其更改为:time_dt = datetime.strptime(time_str, '%H:%M') 然后我会收到有关 strftime 和 1900 年之前的年份的错误。
所以我在这里难住了。需要做什么才能在输入字符串中只允许一个时间?
最佳答案
您可以尝试使用 dateutil
包。 parser.parse()
方法适用于输入字符串发生变化的情况。如果在字符串中仅指定时间,它将构造一个具有今天日期的日期时间对象。它将处理各种其他格式。
from datetime import datetime
from dateutil import parser
def get_local_time(time_str):
"""
takes a string in the format of '27 March at 3:00' which is UTC
and converts it to local time and AM/PM
:param time_str:
"""
offset = datetime.now() - datetime.utcnow()
time_dt = parser.parse(time_str)
return (time_dt + offset).strftime('%I:%M %p')
如果您仅限于日期时间包,您可以这样做:
from datetime import datetime
def get_local_time(time_str):
"""
takes a string in the format of '27 March at 3:00' which is UTC
and converts it to local time and AM/PM
:param time_str:
"""
if len(time_str) <= 5:
time_str = datetime.now().strftime('%d %B at ') + time_str
offset = datetime.now() - datetime.utcnow()
time_dt = datetime.strptime(time_str, '%d %B at %H:%M')
return (time_dt + offset).strftime('%I:%M %p')
print get_local_time('27 March at 3:00')
print get_local_time('3:00')
或者你可以这样做:
from datetime import datetime
def get_local_time(time_str):
"""
takes a string in the format of '27 March at 3:00' which is UTC
and converts it to local time and AM/PM
:param time_str:
"""
offset = datetime.now() - datetime.utcnow()
if len(time_str) <= 5:
time_dt = datetime.combine(datetime.now().date(), datetime.strptime(time_str, '%H:%M').time())
else:
time_dt = datetime.strptime(time_str, '%d %B at %H:%M')
return (time_dt + offset).strftime('%I:%M %p')
print get_local_time('27 March at 3:00')
print get_local_time('3:00')
关于Python的日期时间转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41867467/