python获取系统当前时间并转utc时间为绝对秒数_如何在Python中将datetime转换为UTC时间戳?...

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.

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.

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.

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)

解决方案

I think you are looking for 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)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值