Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

need to convert UTC (aws ec2) to PST in Python

Tags:

I need to convert UTC time, (on ec2 instance) to PST. I am trying to do this.

from datetime import datetime from pytz import timezone import pytz  date_format='%m/%d/%Y %H:%M:%S %Z' date = datetime.now() print 'Current date & time is:', date.strftime(date_format)  my_timezone=timezone('US/Pacific')  date = my_timezone.localize(date) date = date.astimezone(my_timezone)  print 'Local date & time is  :', date.strftime(date_format) 

But the output is:

Current date & time is: 01/10/2012 20:01:14 Local date & time is  : 01/10/2012 20:01:14 PST 

Any reason why I am not getting the right PST time?

like image 935
Nish Avatar asked Jan 10 '12 20:01

Nish


People also ask

How do you convert UTC time to other timezone in Python?

Get the current time using the datetime. now() function(returns the current local date and time) and pass the timezone() function(gets the time zone of a specific location) with the timezone as an argument to it say 'UTC'. Format the above DateTime using the strftime() and print it.

How does Python handle UTC time?

Getting the UTC timestampdatetime. now() to get the current date and time. Then use tzinfo class to convert our datetime to UTC. Lastly, use the timestamp() to convert the datetime object, in UTC, to get the UTC timestamp.


1 Answers

from datetime import datetime from pytz import timezone import pytz  date_format='%m/%d/%Y %H:%M:%S %Z' date = datetime.now(tz=pytz.utc) print 'Current date & time is:', date.strftime(date_format)  date = date.astimezone(timezone('US/Pacific'))  print 'Local date & time is  :', date.strftime(date_format) 

seems to work for me :) - timezones are confusing, slowly making a plan of what I actually want to do helps me most of the time

like image 122
sleeplessnerd Avatar answered Nov 10 '22 13:11

sleeplessnerd