如何在Python中将日期时间转换为UTC时间戳?
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了如何在Python中将日期时间转换为UTC时间戳?,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含1548字,纯文字阅读大概需要3分钟。
内容图文
从http://docs.python.org/library/time.html开始:
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中指定;我不想在包装盒上使用当地时区.
从日期时间到时间戳记,我可以将时间视为UTC吗?我希望能够在与时间戳进行相互转换时将所有内容保持在规范化的UTC形式(datetime对象)中.
我希望能够做这样的事情,让x和y表现出相同的效果:
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中将日期时间转换为UTC时间戳?全部内容,希望文章能够帮你解决如何在Python中将日期时间转换为UTC时间戳?所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。