这是我的代码:
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年前的年份的错误。
所以我很难过。在输入字符串中只需要一段时间需要做什么?
答案 0 :(得分:2)
您可以尝试使用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')
答案 1 :(得分:2)
我刚刚在repl中尝试过。它对我有用:
>>> from datetime import datetime
>>> time = "02:00"
>>> time_dt = datetime.strptime(time, '%H:%M')
>>> time_dt
datetime.datetime(1900, 1, 1, 2, 0)
>>>
如果我没记错,日期时间永远不会只一次,总会有一个假日期为1900年1月1日。如果你想存储没有虚拟日期的时间,试试使用time
类。它还有一个strftime函数,请参阅此处的文档:https://docs.python.org/2/library/time.html
如果不能正常工作,您还可以尝试为日期时间添加不同的虚拟日期。