0

How can I convert UTC to Pacific time zone in Python?

I tried this but it is not working

from datetime import datetime
from pytz import timezone

fmt = "%Y-%m-%d %H:%M:%S %Z%z"

# Current time in UTC
now_utc = 1348283733848

# Convert to US/Pacific time zone
now_pacific = now_utc.astimezone(timezone('US/Pacific'))
print now_pacific.strftime(fmt)

Error:

Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
AttributeError: 'long' object has no attribute 'astimezone

I want to convert this UTC 1348283733848 to pacific time zone in human readble format

FObersteiner
  • 22,500
  • 8
  • 42
  • 72
  • Please post the error message you got. – Erik Cederstrand Apr 05 '18 at 11:33
  • possible duplication of https://stackoverflow.com/questions/38861426/unix-timestamp-to-iso-8601-time-format?utm_medium=organic&utm_source=google_rich_qa&utm_campaign=google_rich_qa – Mehrdad Pedramfar Apr 05 '18 at 11:37
  • @ErikCederstrand this is the error message Traceback (most recent call last): File "", line 2, in AttributeError: 'long' object has no attribute 'astimezone – Rakesh moorthy Apr 05 '18 at 11:37
  • 1
    `now_utc` is a `long` because you didn't quote it. You need to make `now_utc` a datetime object, not a string or integer. Presumably, you would need to find a `fmt` string that matches, or skip the timezone part and just convert the timestamp value to a datetime. – Erik Cederstrand Apr 05 '18 at 11:41
  • 1
    This works: `now_pacific = datetime.fromtimestamp(now_utc / 1000, tz=timezone('UTC')).astimezone(timezone('US/Pacific'))`, but the date / time is kind of far away from "*now*". Not sure if this is what you want. – CristiFati Apr 05 '18 at 11:45
  • @CristiFati this works – Rakesh moorthy Apr 05 '18 at 11:50

2 Answers2

0

you can use

datetime.utctimestamp(now_utc).strftime("%H:%M:%S %Z%")
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
prachi
  • 83
  • 2
  • 11
-1

maybe do

datetime.datetime.utcfromtimestamp(now_utc) - datetime.timedelta(hours=8)
altamont
  • 353
  • 4
  • 8
  • 2
    Offset arithmetic is 1000% wrong - what about DST? Your answer is wrong half the year. That's why `.astimezone(timezone('US/Pacific'))` is used to convert the time using the timezone's rules. DST rules change all the time too - Russia changed its rules twice a few years back. Egypt changed its rules with only a few weeks warning. – Panagiotis Kanavos Jan 12 '22 at 07:54