2010-08-25 152 views
3

嘿,大家好!我有时区麻烦。Python unix时间戳转换和时区

我的2010-07-26 23时35分03秒

时间戳我真正想要做的就是从那个时候减去15分钟。

我的方法是将是一个简单的转换UNIX时间,减去秒,转换回。简单的权利?

我的问题是,蟒蛇使用我的本地时区,目前东部夏令时间,我相信调整返回的UNIX时间是北京时间。

所以,当我这样做:

# packet[20] holds the time stamp 

unix_time_value = (mktime(packet[20].timetuple())) 

我得到1280201703这是星期二,2010年7月27日3时35分03秒。我可以这样做:

unix_time_value = (mktime(packet[20].timetuple())) - (4 * 3600) 

,但现在我要检查这是-5 GMT东部标准时间和调整(4 * 3600)至(5 * 3600)。有什么办法可以告诉python不要使用我的本地时区,只需要转换darn时间戳,还是有一种简单的方法来接收数据包[20]并减去15分钟?

回答

6

datetime.timedelta(seconds=15*60)

6

online docs有一个方便的表格(你称之为“unix时间”更恰当地称为“UTC”,“通用时间坐标”,并且“自时代以来的秒数”是作为浮点数的“时间戳记”。 。):

使用下列功能时之间转换 :

From      To       Use 

seconds since the epoch  struct_time in UTC   gmtime() 

seconds since the epoch  struct_time in local time localtime() 

struct_time in UTC   seconds since the epoch  calendar.timegm() 

struct_time in local time seconds since the epoch  mktime() 

其中不合格的函数名来自time模块(因为这其中的文档是; - )。所以,既然你显然有struct_time in UTC启动,使用calendar.timegm()获得时间戳(又名“自纪元秒”),减去15 * 60 = 900(因为度量的单位是秒),并把产生的“秒从纪元”回一个struct_time in UTCtime.gmtime。或者,使用time.mktimetime.localtime如果你喜欢在本地时间的工作(但可能给问题,如果15分钟就可以横跨在切换到DST或背面的瞬间 - 总是UTC工作是发声器)。

当然,要使用calendar.timegm,您需要在代码中使用import calendar(导入通常最好放置在脚本或模块的顶部)。

+0

很好的解释。谢谢! – 2010-08-25 15:45:01