转换为UTC时间戳 [英] Convert to UTC Timestamp

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

问题描述

//parses some string into that format.
datetime1 = datetime.strptime(somestring, "%Y-%m-%dT%H:%M:%S")

//gets the seconds from the above date.
timestamp1 = time.mktime(datetime1.timetuple())

//adds milliseconds to the above seconds.
timeInMillis = int(timestamp1) * 1000

我该怎么做(在那一点上代码)将日期转换为UTC格式?我一直在努力寻找API,似乎已经有一个世纪了,找不到我可以使用的任何东西。有人可以帮忙吗?我相信目前已经变成了东部时间(但是我现在是格林尼治标准时间,但想要UTC)。

How do I (at any point in that code) turn the date into UTC format? I've been ploughing through the API for what seems like a century and cannot find anything that I can get working. Can anyone help? It's currently turning it into Eastern time i believe (however I'm in GMT but want UTC).

编辑:我给了最接近那个家伙的答案我终于找到了。

I gave the answer to the guy with the closest to what I finally found out.

datetime1 = datetime.strptime(somestring, someformat)
timeInSeconds = calendar.timegm(datetime1.utctimetuple())
timeInMillis = timeInSeconds * 1000

:)

推荐答案

def getDateAndTime(seconds=None):
 """
  Converts seconds since the Epoch to a time tuple expressing UTC.
  When 'seconds' is not passed in, convert the current time instead.
  :Parameters:
      - `seconds`: time in seconds from the epoch.
  :Return:
      Time in UTC format.
"""
return time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime(seconds))`

这会将本地时间转换为UTC

This converts local time to UTC

time.mktime(time.localtime(calendar.timegm(utc_time)))

http://feihonghsu.blogspot.com/2008/02/converting-from-local-time-to-utc.html

如果使用mktime将struct_time转换为秒(因为历元),则该
转换在当地时区 em>。没有办法告诉它使用任何特定的时区,而不仅仅是UTC。标准的时间包始终假定您所在的时区在您所在的时区。

If converting a struct_time to seconds-since-the-epoch is done using mktime, this conversion is in local timezone. There's no way to tell it to use any specific timezone, not even just UTC. The standard 'time' package always assumes that a time is in your local timezone.

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

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