Click here to Skip to main content
15,912,665 members
Articles / Programming Languages / Python
Tip/Trick

Local Time to UTC Time in Python

Rate me:
Please Sign up or sign in to vote.
3.32/5 (4 votes)
21 Aug 2016CPOL 9.5K   1  
Time from local to utc

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:

C++
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

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
China China
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
-- There are no messages in this forum --