Python is a popular programming language. There are many inbuilt functions and modules that can make your task easier. The datatime module is one of them. It allows you to manipulate date and time. In this entire tutorial, you will know how to convert UTC to Local Time in Python using various methods.
Methods to Convert UTC to Local Time in Python
In this section, you will know all the methods to convert UTC to local time. Please be sure that you should do all your work on Jupyter Notebook as I am also doing on it. It’s for a better understanding of the output and the code.
Method 1: Using astimezone() function
The first method is the use of astimezone() function. It will use in combination with the tzlocal module. Execute the below lines of code.
from datetime import datetime from dateutil.tz import tzutc, tzlocal utc = datetime.now(tzutc()) print('UTC TIME: ' + str(utc)) local = utc.astimezone(tzlocal()) print('Local TIME: ' + str(local))
Explanation of the code
Here first Import dateime,tzutc and tzlocal python module. After that using the datetime.now(tzutc()), I am getting the current UTC date and time. To convert the UTC time to local time I am using the dot operator on UTC time and passing the tzlocal() method inside the astimezone() function. When you will run the code you will get the following output.
Method 2: Convert UTC to Local Time using datetime only
The second method to convert is using the datetime module only. Here you will also use the pytz.timezone() function with the local time zone as an argument. You can get all the time zone list using the pytz.all_timezones. For example, in my case, I am using Asia/Kolkata Timezone. Copy and paste the below lines of code and see the output.
import datetime from datetime import datetime utc_datetime = datetime.now(tzutc()) local_timezone = pytz.timezone('Asia/Kolkata') local_datetime = local_datetime.astimezone(local_timezone) print(local_datetime)
These are the methods I have compiled to convert Convert UTC to Local Time in Python. You can use any method you want as per convenience. I hope you have liked this tutorial. If you have any queries then you can contact us for more help and information.
Other Datetime Related Post –
Join our list
Subscribe to our mailing list and get interesting stuff and updates to your email inbox.