How to get UTC time in Python
In this tutorial, we will learn how to get UTC timezone time in Python. we will use datetime library of Python. From this library, we use the pytz module to fetch UTC time. datetime module will help to find the date and time. For a better understanding of datetime module check this tutorial datetime in Python.
Firstly, we will see to get date and time using datetime library.
Example Code:
import datetime #creating datetime object da = datetime.date.today() dt = datetime.datetime.now() #printing the current exact time print(da) print(dt)
Output:
2022-01-26 2022-01-26 19:40:13.850430
Now we will use pytz(python time zone) module to convert the current time to UTC timezone.
# importing all required libraries import pytz import datetime #creating datetime object dt = datetime.datetime.now() #printing the current exact time print(dt) #Now we convert this time to UTC ut = datetime.datetime.now(pytz.utc) # utt = ut.timestamp() #now we print UTC time print(ut)
Output:
2022-01-26 22:51:16.596603 2022-01-26 17:21:16.596616+00:00
Leave a Reply