Python提供了不同的包(datetime, time, calendar)来处理时间。我犯了一个大错误,使用以下命令获取当前的GMT时间time.mktime(datetime.datetime.utcnow().timetuple()))
用Unix时间戳获取当前格林尼治时间的简单方法是什么?
Python提供了不同的包(datetime, time, calendar)来处理时间。我犯了一个大错误,使用以下命令获取当前的GMT时间time.mktime(datetime.datetime.utcnow().timetuple()))
用Unix时间戳获取当前格林尼治时间的简单方法是什么?
当前回答
import time
int(time.time())
输出:
1521462189
其他回答
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!
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()
import time
int(time.time())
输出:
1521462189
我将使用time.time()来获得一个时间戳,以秒为单位。
import time
time.time()
输出:
1369550494.884832
对于大多数平台上的标准CPython实现,这将返回一个UTC值。
这有用吗?
from datetime import datetime
import calendar
d = datetime.utcnow()
unixtime = calendar.timegm(d.utctimetuple())
print unixtime
如何将Python UTC日期时间对象转换为UNIX时间戳