Python unix时间戳转换和时区

Wil*_*ild 3 python

大家好!我遇到了时区问题.

我的时间戳是2010-07-26 23:35:03

我真正想做的是从那时起减去15分钟.

我的方法是简单转换为unix时间,减去秒数并转换回来.简单吧?

我的问题是python使用我的本地时区调整返回的unix时间,目前东部夏令时,我认为是GMT -4.

所以当我这样做时:

 # packet[20] holds the time stamp

 unix_time_value = (mktime(packet[20].timetuple())) 
Run Code Online (Sandbox Code Playgroud)

我得到1280201703,这是星期二,2010年7月27日03:35:03.我可以做这个:

 unix_time_value = (mktime(packet[20].timetuple())) - (4 * 3600)
Run Code Online (Sandbox Code Playgroud)

但现在我必须检查东部标准时间-5 GMT并将(4*3600)调整为(5*3600).有没有办法告诉python不使用我的本地时区只是转换时间戳或者有一个简单的方法来获取数据包[20]并减去15分钟?

Ign*_*ams 6

减去datetime.timedelta(seconds=15*60).


Ale*_*lli 6

在线文档有一个方便的表(你所说的"UNIX时间"更恰当地称为"UTC",为"通用协调时间"和"秒从纪元"是一个"时间戳"为float ...):

使用以下函数在时间表示之间进行转换:

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()
Run Code Online (Sandbox Code Playgroud)

其中不合格的函数名称来自time模块(因为那是文档的位置;-).因此,因为你显然是以a开头struct_time in UTC,calendar.timegm()用来获取时间戳(AKA"自纪元以来的秒数"),减去15 * 60 = 900(因为度量单位是秒),并将得到的"自纪元以来的秒数"放回到struct_time in UTCwith中time.gmtime.或者,使用time.mktime并且time.localtime如果您更喜欢在当地时间工作(但如果15分钟可以跨越它切换到DST或返回的瞬间,那么这可能会产生问题 - 始终在UTC中工作更加健全).

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