Python提供了不同的包(datetime, time, calendar)来处理时间。我犯了一个大错误,使用以下命令获取当前的GMT时间time.mktime(datetime.datetime.utcnow().timetuple()))

用Unix时间戳获取当前格林尼治时间的简单方法是什么?


这有用吗?

from datetime import datetime
import calendar

d = datetime.utcnow()
unixtime = calendar.timegm(d.utctimetuple())
print unixtime

如何将Python UTC日期时间对象转换为UNIX时间戳


我将使用time.time()来获得一个时间戳,以秒为单位。

import time

time.time()

输出:

1369550494.884832

对于大多数平台上的标准CPython实现,这将返回一个UTC值。


我喜欢这个方法:

import datetime, time

dts = datetime.datetime.utcnow()
epochtime = round(time.mktime(dts.timetuple()) + dts.microsecond/1e6)

这里发布的其他方法要么不保证在所有平台上为您提供UTC,要么只报告整个秒数。如果你想要完整的分辨率,这个可以做到微秒级。


或者仅仅使用datetime标准模块

In [2]: from datetime import timezone, datetime
   ...: int(datetime.now(tz=timezone.utc).timestamp() * 1000)
   ...: 
Out[2]: 1514901741720

您可以根据所需的分辨率进行截断或相乘。这个例子是输出millis。

如果你想要一个合适的Unix时间戳(以秒为单位),可以去掉* 1000


import time

int(time.time()) 

输出:

1521462189

from datetime import datetime as dt
dt.utcnow().strftime("%s")

输出:

1544524990

#First Example:
from datetime import datetime, timezone    
timstamp1 =int(datetime.now(tz=timezone.utc).timestamp() * 1000)
print(timstamp1)

输出:1572878043380

#second example:
import time
timstamp2 =int(time.time())
print(timstamp2)

输出:1572878043

在这里,我们可以看到第一个例子给出的时间比第二个更准确。 这里我用的是第一个。


Python2和python3

使用时间模块是很好的

import time
int(time.time())

1573708436

你也可以使用datetime模块,但是当你使用strftime('%s')时,strftime会将时间转换为你的本地时间!

python2

from datetime import datetime
datetime.utcnow().strftime('%s')

python3

from datetime import datetime
datetime.utcnow().timestamp()

至少在python3中,这是有效的:

>>> datetime.strftime(datetime.utcnow(), "%s")
'1587503279'

Python 3秒微秒十进制分辨率:

from datetime import datetime
print(datetime.now().timestamp())

Python 3整数秒:

print(int(datetime.now().timestamp()))

datetime.utcnow().timestamp()警告!

Datetime.utcnow()是非时区感知对象。参考资料:https://docs.python.org/3/library/datetime.html#aware-and-naive-objects

例如UTC凌晨1点:

from datetime import timezone
print(datetime(1970,1,1,1,0,tzinfo=timezone.utc).timestamp())

or

print(datetime.fromisoformat('1970-01-01T01:00:00+00:00').timestamp())

if you remove the tzinfo=timezone.utc or +00:00, you'll get results dependent on your current local time. Ex: 1am on Jan 1st 1970 in your current timezone - which could be legitimate - for example, if you want the timestamp of the instant when you were born, you should use the timezone you were born in. However, the timestamp from datetime.utcnow().timestamp() is neither the current instant in local time nor UTC. For example, I'm in GMT-7:00 right now, and datetime.utcnow().timestamp() gives a timestamp from 7 hours in the future!