Abhilash Joseph
Abhilash Joseph

Reputation: 1196

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.

Upvotes: 9

Views: 18891

Answers (2)

famousgarkin
famousgarkin

Reputation: 14126

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.

Upvotes: 26

Sar009
Sar009

Reputation: 2276

set the timezone to UTC in your settings.py. Get the user input of time and timezone in certain format. Suppose you get the user time as 'Jul-7-2014 12:35PM:30' (consider using date input in your html).

from datetime import datetime, timedelta

// convert the time to standard format
user_date = datetime.strptime('Jul-7-2014 12:35PM:30', '%b-%d-%Y %I:%M%p:%S')
user_date_string = user_date.strftime('%Y-%m-%d %H:%M:%S')
// save the time to model with users timezone

// now when user asks back for his time, add the timezone with timedelta
user_date = datetime.strptime(user_date_string, '%Y-%m-%d %H:%M:%S') 
user_date = user_date + timedelta(hours = 5, minutes = 30)
// finally display it
print user_data.strftime('%Y-%m-%d %H:%M:%S')

*this is not considering django inbuild datetime functions which returns datetime object for datetime model field. If implemented that it will be more simple

Upvotes: 0

Related Questions