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

Question:

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?

Asked By: Nish

||

Answers:

I think you want datetime.utcnow() if you are attempting to simulate UTC time in your example.

The other issue is that by default the object has no timezone. This does not mean that it is UTC, and I think pytz is just defaulting to localtime for that object. You need to create a new datetime object with the timezone set as UTC before you try to convert it to PST.

You can do this via

date = datetime.utcnow()
date.replace(tzinfo=pytz.utc)
Answered By: Michael Merickel
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

Answered By: sleeplessnerd

By calling to localize you tell in what TZ your time is. So, in your example you say that your date is in PST, then you call astimezone for PST and get the same time which is expected. You probably need the following:

utc_dt = pytz.utc.localize(datetime.utcnow())
pst_tz = timezone('US/Pacific')
pst_dt = pst_tz.normalize(utc_dt.astimezone(pst_tz))
pst_dt.strftime(fmt)

Sorry, cannot check if this code executes – don’t have this library on workstation.

Answered By: real4x

if you want to calculate the current uptime based on launchtime of an EC2 instance, one can try this:

import datetime
lt_datetime = datetime.datetime.strptime(inst.launch_time, '%Y-%m-%dT%H:%M:%S')
lt_delta = datetime.datetime.utcnow() - lt_datetime
str(lt_delta)
Answered By: andpei

Do this in one line:

>>> import pytz
>>> pytz.utc.localize(datetime.utcnow()).astimezone(pytz.timezone('US/Pacific'))
datetime.datetime(2016, 5, 16, 10, 58, 18, 413399, tzinfo=<DstTzInfo 'US/Pacific' PDT-1 day, 17:00:00 DST>)
Answered By: Wayne Ye
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.