gpt4 book ai didi

python - 如何在Python中存储没有日期的时间以便比较方便?

转载 作者:行者123 更新时间:2023-11-28 20:18:30 25 4
gpt4 key购买 nike

我有一个简单的任务,即在服务器的时区中存储一个时间,然后比较当前时间是在保存的时间之前还是之后。

我尝试将时间存储为“2008 年 1 月 1 日”日期以及我需要的时间。问题是夏令时有问题,如果我在 1 月 1 日保存“16:00”并尝试将其与 4 月 1 日的“16:00”进行比较,我会得到一个小时的差异。我希望“16:00”始终表示当天的“16:00”。

什么是存储和比较一天中的时间并忽略日期的有效且可靠的方法?我需要它也是 json 序列化的,这样我就可以在需要时轻松地在 python 和 JS 中操作值。

最佳答案

I need it to also be json-serializable, so I can easily manipulate the value in python and JS if needed.

"16:00" 字符串可用于存储时间(如果您不需要秒)。

I want "16:00" to always mean current day's "16:00".

与当前时间比较:

import time

if time.strftime('%H:%M') < '16:00':
print('before 4pm')
else:
print('after 4pm')

%H%M 生成零填充的十进制数字,例如 07,因此字符串比较工作正常。它也适用于 DST 转换(只要 C localtime() 有效)。

将其解析为时间、日期时间对象:

from datetime import datetime

four_pm_time = datetime.strptime('16:00', '%H:%M').time()
four_pm = datetime.combine(datetime.now(), four_pm_time)

获取时区感知的日期时间对象:

import tzlocal # $ pip install tzlocal

four_pm_aware = tzlocal.get_localzone().localize(four_pm, is_dst=None)

To get Unix time corresponding to 4pm (assuming mktime() works here) :

import time

unix_time = time.mktime(time.localtime()[:3] + (16, 0, 0) + (-1,)*3)

关于python - 如何在Python中存储没有日期的时间以便比较方便?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36414920/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com