简体   繁体   中英

datetime.utcnow() is off by 1 Hour

Why is utcnow off by 1 hour??

Code:

from datetime import *
print datetime.utcnow()

result:

2016-11-25 10:28:04.655978

Servertime:

Fri Nov 25 11:28:11 CET 2016

Because CET is UTC + 1

Check this link to see the conversion: http://www.worldtimebuddy.com/utc-to-cet-converter

datetime.utcnow() returns UTC (Coordinated Universal Time) time : UTC Time definition

To get the same time as your server use datetime.now() .

In [8]: from datetime import datetime

In [9]: datetime.utcnow()
Out[9]: datetime.datetime(2016, 11, 25, 10, 32, 18, 288195)

In [10]: datetime.now()
Out[10]: datetime.datetime(2016, 11, 25, 11, 32, 22, 336213)

This was happened because your server in different time zone. (CET = +1)

>>> from datetime import datetime
>>> 
>>> datetime.utcnow()
datetime.datetime(2016, 11, 25, 10, 35, 33, 931951)
>>> 

use pytz module to change timezone

pip install pytz

you can also use timezone like

from datetime import datetime
from pytz import timezone

fmt = "%Y-%m-%d %H:%M:%S %Z%z"

# Current time in UTC
now_utc = datetime.now(timezone('UTC'))
print now_utc.strftime(fmt)

# Convert to US/Pacific time zone
now_pacific = now_utc.astimezone(timezone('US/Pacific'))
print now_pacific.strftime(fmt)

# Convert to Europe/Berlin time zone
now_berlin = now_pacific.astimezone(timezone('Europe/Berlin'))
print now_berlin.strftime(fmt)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM