Python的日期时间转换
作者:互联网
这是我的代码:
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()方法会很好.如果在字符串中仅指定时间,它将使用今天的日期构造一个datetime对象.它将处理各种其他格式.
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-datetime,python-2-7,python 来源: https://codeday.me/bug/20191026/1935499.html