Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / Python

Local Time to UTC Time in Python

3.32/5 (4 votes)
21 Aug 2016CPOL 9.6K  
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)