简体   繁体   English

python2.7中的时间偏移

[英]Time offset in python2.7

I'm trying to shift a time forward or backward depending on some integer value. 我试图根据一些整数值向前或向后移动时间。 So far, I've been just adding (or subtracting) that time shift from the hour then using mod 24 when I create the time 到目前为止,我只是从小时中添加(或减去)该时移,然后在创建时间时使用mod 24

time_structure = datetime.time((hour + time_zone_shift)%24, minute, second) 

This works for the most part (except with rolling back the date, ie if the time given is 7:30 and then the time_zone_shift is -8). 这在大多数情况下都有效(除非回滚日期,即给定的时间是7:30,然后time_zone_shift是-8)。 I was wondering if there is a more "pythonic" way to do this? 我想知道是否有更“ pythonic”的方式来做到这一点?

So to answer your question, you should use datetime.timedelta to offset a time: 因此,要回答您的问题,您应该使用datetime.timedelta来偏移时间:

time_structure = (datetime.datetime(0, 0, 0, hour, minute, second) + datetime.timedelta(hours=time_zone_shift)).time()

But as expressed in the comments, you should really use pytz for time zone math since it can be rather complicated. 但是正如评论中所表达的那样,您应该在时区数学中真正使用pytz ,因为它可能相当复杂。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM