This tutorial will cover a few ways you can convert a datetime object to UTC in python.
Converting a datetime object to UTC is a common and important part of modern software development. Server time and dates stored in databases are often in UTC, so converting a date to UTC is something that not only python developers, but pretty much any developer will find themselves doing time and time again.
So, I thought I’d write down a few ways that you can do this datetime to UTC conversion in python.
Let’s get down to business.
Datetime astimezone Function
The first method for converting a datetime to UTC will involve using the astimezone function of your datetime object.
We are are also going to use the pytz package to reference the UTC timezone.
The example looks like this:
As you can see, converting a datetime to UTC is not all that difficult. Though it’s a bit annoying that you always have to import the pytz package.
Also, please note that this example assumes your datetime object is timezone aware. If it is not, you will need to make your naive datetime object timezone aware. If you are unsure how to do this, please read my article How To Make A Naive Datetime object Timezone Aware In Python.
Ok, now let’s move onto the next method which is my favorite.
Using the Arrow Package
The next method uses the python arrow package. Take a look at how arrow handles the same problem:
That’s it! I love how easy arrow makes this. It’s awesome being able to specify the UTC timezone as a string. I highly recommend using arrow because of how clean and convenient it is. Just as with the above example, you should also make sure that your datetime object is time zone aware.
And that’s all folks!
If you liked this and want to read more python content, here are some other python articles I wrote.