Introduction
This is a little tip about how to format your local time to utc time using Python.
Background
We have a web project which uses MongoDB as database. In MongoDB, if a field's type is datetime
, it will be automatically formatted to utc. And the problem is that it only changes the type, but does not change your time.
For example, it is 2016-08-22 09:40:00
in Beijing time. And it will be stored as ISODate("2016-08-22T09:40:00.000Z")
.
Using the Code
As the problem described above, we need to write a method to change our time from local to utc.
The code is like this:
def local_to_utc(t):
time_s = datetime.datetime.strptime(t, "%Y%m%d")
secs = time.mktime(time_s.timetuple())
return datetime.datetime.fromtimestamp(time.mktime(time.gmtime(secs)))
History
- 22nd August, 2016: Initial version