如何在Python中将datetime转换为UTC时间戳? [英] How do I convert a datetime to a UTC timestamp in Python?

查看:1189
本文介绍了如何在Python中将datetime转换为UTC时间戳?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

http://docs.python.org/library/time.html


time.mktime(t):
这是localtime()的反向函数。它的参数是
struct_time或完整的9元组(因为需要
dst标志;使用-1作为dst
标志,如果它是未知的),表示
的时间在当地时间,而不是UTC。它
返回一个浮点数,对于
与time()的兼容性。如果
输入值不能表示为
有效时间,则会引发OverflowError或
ValueError(其中
取决于无效值
是否被Python或底层的
C库)。
的最早日期可以产生一个时间是
平台依赖。

time.mktime(t): This is the inverse function of localtime(). Its argument is the struct_time or full 9-tuple (since the dst flag is needed; use -1 as the dst flag if it is unknown) which expresses the time in local time, not UTC. It returns a floating point number, for compatibility with time(). If the input value cannot be represented as a valid time, either OverflowError or ValueError will be raised (which depends on whether the invalid value is caught by Python or the underlying C libraries). The earliest date for which it can generate a time is platform-dependent.

这就说明你需要在本地时间指定你的时间元组,而不是UTC。但是,我想在UTC中指定;我不想在框上使用本地时区。

This says you need to specify your time tuple in local time, not UTC. However, I want to specify in UTC; I don't want to use the local time zone on the box.

有没有什么办法可以从日期时间到时间戳,其时间被视为世界标准时间?当我转换到和从时间戳来,我希望能够将所有内容都保存在一个标准化的UTC格式(datetime对象)中。

Is there any way that I can go from datetime to a timestamp, where the time is treated as UTC? I want to be able to keep everything in a normalized UTC form (datetime object) when I convert to and from timestamps.

我希望能够这样做并且x和y出来一样:

I want to be able to do something like this and have x and y come out the same:

 y = datetime.datetime.utcfromtimestamp(time.mktime(x.timetuple()))
 x = dateutil.parser.parse('Wed, 27 Oct 2010 22:17:00 GMT')
 stamp = time.mktime(x.timetuple())
 y = datetime.datetime.utcfromtimestamp(stamp)
 x
datetime.datetime(2010, 10, 27, 22, 17, tzinfo=tzutc())
 y
datetime.datetime(2010, 10, 28, 6, 17)


推荐答案

我想你是寻找 calendar.timegm

import datetime
import dateutil.parser
import calendar

x = dateutil.parser.parse('Wed, 27 Oct 2010 22:17:00 GMT')
stamp = calendar.timegm(x.timetuple())
y = datetime.datetime.utcfromtimestamp(stamp)
print(repr(x))
# datetime.datetime(2010, 10, 27, 22, 17, tzinfo=tzutc())

print(repr(y))
# datetime.datetime(2010, 10, 27, 22, 17)

这篇关于如何在Python中将datetime转换为UTC时间戳?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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