Python 的日期时间转换

Python's datetime conversion

这是我的代码:

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,这只是时间,不包括 day/month。即:“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')

我刚刚在 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 class。它还有一个 strftime 函数,请参阅此处的文档:https://docs.python.org/2/library/time.html

如果它不起作用,您也可以尝试向日期时间添加不同的虚拟日期。