对于python,如何将UTC区域中的DatetimeField(具有本地服务器时间)转换为datetimefield?
The best that I can come up with is to convert it to a timestamp and then use the datetime.utcfromtimestamp
class method
import time
import datetime
def to_utc(dateTime)
timeStamp = time.mktime(dateTime.timetuple()) + dateTime.microsecond
return datetime.datetime.utcfromtimestamp(timeStamp)
>>> import datetime
>>> import pytz
>>> datetime.datetime.now(pytz.timezone('Europe/Minsk'))
datetime.datetime(2011, 8, 8, 15, 32, 7, 816893, tzinfo=<DstTzInfo 'Europe/Minsk' EEST+3:00:00 DST>)
>>> x = datetime.datetime.now()
>>> x
datetime.datetime(2011, 8, 8, 15, 32, 26, 960839)
>>> x.replace(tzinfo=pytz.timezone('Europe/Minsk'))
datetime.datetime(2011, 8, 8, 15, 32, 26, 960839, tzinfo=<DstTzInfo 'Europe/Minsk' MMT+1:50:00 STD>)
>>> x.replace(tzinfo=pytz.timezone('Europe/Minsk')).isoformat()
'2011-08-08T15:32:26.960839+01:50'
>>> datetime.datetime.now(pytz.timezone('Europe/Minsk')).isoformat()
'2011-08-08T15:33:16.720865+03:00'
Compare plz :) replace is not a good idea. The best is to convert to timestamp and then to datetime again.
Best idea:
pytz.timezone('Europe/Minsk').localize(datetime.datetime.now())
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.