Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Convert time to UTC format

from django.utils import timezone
time_zone = timezone.get_current_timezone_name() # Gives 'Asia/Kolkata'
date_time = datetime.time(12,30,tzinfo=pytz.timezone(str(time_zone)))

Now I need to convert this time to UTC format and save it in Django model. I am not able to use date_time.astimezone(pytz.timezone('UTC')). How can I convert the time to UTC. Also Back to 'time_zone'.

This is a use case when user type time in a text box and we need to save time time in UTC format. Each user will also select his own time zone that we provide from Django timezone module.

Once the user request back the saved time it must be shown back to him in his selected time zone.

like image 417
Abhilash Joseph Avatar asked Jul 12 '14 06:07

Abhilash Joseph


People also ask

How do you convert time to UTC in Python?

Use the pytz module, which comes with a full list of time zones + UTC. Figure out what the local timezone is, construct a timezone object from it, and manipulate and attach it to the naive datetime. Finally, use datetime. astimezone() method to convert the datetime to UTC.

How do you convert datetime to UTC?

To convert the time in a non-local time zone to UTC, use the TimeZoneInfo. ConvertTimeToUtc(DateTime, TimeZoneInfo) method. To convert a time whose offset from UTC is known, use the ToUniversalTime method. If the date and time instance value is an ambiguous time, this method assumes that it is a standard time.

How do I print the UTC date in Python?

Simply use datetime. datetime. utcnow(). strftime("%a %b %d %H:%M:%S %Z %Y") can solve your problem already.

How do I change timezone in Python?

I have found that the best approach is to convert the "moment" of interest to a utc-timezone-aware datetime object (in python, the timezone component is not required for datetime objects). Then you can use astimezone to convert to the timezone of interest (reference).


1 Answers

These things are always easier using complete datetime objects, e.g.:

import datetime
import pytz

time_zone = pytz.timezone('Asia/Kolkata')

# get naive date
date = datetime.datetime.now().date()
# get naive time
time = datetime.time(12, 30)
# combite to datetime
date_time = datetime.datetime.combine(date, time)
# make time zone aware
date_time = time_zone.localize(date_time)

# convert to UTC
utc_date_time = date_time.astimezone(pytz.utc)
# get time
utc_time = utc_date_time.time()

print(date_time)
print(utc_date_time)
print(utc_time)

Yields:

2014-07-13 12:30:00+05:30
2014-07-13 07:00:00+00:00
07:00:00

right now for me.

like image 124
famousgarkin Avatar answered Nov 15 '22 19:11

famousgarkin