如何在Python中存储没有日期的时间,以便比较? [英] How to store time without date in Python so it's convenient to compare?

查看:47
本文介绍了如何在Python中存储没有日期的时间,以便比较?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a simple task of storing a time in server's timezone and then comparing if current time if after or before the saved time.

我尝试将时间与所需时间存储为"2008年1月1日".问题是,夏令时变得有些麻烦,如果我在1月1日保存"16:00"并尝试将其与4月1日的"16:00"进行比较,我会得到一个小时的差异.我希望"16:00"始终表示当天的"16:00".

I tried to store the time as a "Jan 1st 2008" date with the time I need. The problem is a daylight saving time gets in a way, if I save "16:00" on Jan 1st and try to compare it with "16:00" on April 1st I get an one hour difference. I want "16:00" to always mean current day's "16:00".

存储和比较一天中的时间并忽略日期的有效而可靠的方法是什么?我还需要它可以json序列化,因此如果需要,我可以轻松地在python和JS中操纵值.

What would be an efficient and reliable way of storing and comparing time of the day and ignoring the date? I need it to also be json-serializable, so I can easily manipulate the value in python and JS if needed.

推荐答案

只需存储您想要的内容,然后使用 datetime 对象的 .time()方法并进行比较.

Just store it however you want, then use the .time() method of the datetime objects and make comparisons.

from datetime import datetime
dt1 = datetime(2008, 1, 1, 16, 0, 0)
dt2 = datetime(2008, 4, 7, 13, 30, 0)

print(dt1.time() > dt2.time())    # True

如果您要对日期时间对象进行挂钟"算法(与时间轴"算法相对应,后者应使用UTC datetime s完成),则也可以将其转换为原始日期时间对象.):

You can also just turn your datetimes into naive datetime objects if you want to do "wall clock" arithmetic on them (as opposed to "timeline" arithmetic, which should be done with UTC datetimes):

from dateutil import tz
from datetime import datetime
NEW_YORK = tz.gettz('America/New_York')
dt = datetime(2008, 1, 1, 16, 0, tzinfo=NEW_YORK)
dt_naive = dt.replace(tzinfo=None)   # datetime(2008, 1, 1, 16)

这篇关于如何在Python中存储没有日期的时间,以便比较?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆