Python Convert time to UTC format

datetime, django, python, timezone

Solution

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.

Problem

``` 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.

Original source