Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

datetime - Localizing Epoch Time with pytz in Python

Im working on converting epoch timestamps to dates in different timezones with pytz. What I am trying to do is create a DateTime object that accepts an Olson database timezone and an epoch time and returns a localized datetime object. Eventually I need to answer questions like "What hour was it in New York at epoch time 1350663248?"

Something is not working correctly here:

import datetime, pytz, time

class DateTime:
    def __init__(self, timezone, epoch):
        self.timezone = timezone
        self.epoch = epoch
        timezoneobject = pytz.timezone(timezone)
        datetimeobject = datetime.datetime.fromtimestamp( self.epoch )
        self.datetime = timezoneobject.localize(datetimeobject)

    def hour(self):
        return self.datetime.hour

if __name__=='__main__':
    epoch = time.time()
    dt = DateTime('America/Los_Angeles',epoch)
    print dt.datetime.hour
    dt = DateTime('America/New_York',epoch)
    print dt.datetime.hour

This prints the same hour, whereas one should be 3 or so hours ahead. Whats going wrong here? I'm a total Python beginner, any help is appreciated!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

datetime.fromtimestamp(self.epoch) returns localtime that shouldn't be used with an arbitrary timezone.localize(); you need utcfromtimestamp() to get datetime in UTC and then convert it to a desired timezone:

from datetime import datetime
import pytz

# get time in UTC
utc_dt = datetime.utcfromtimestamp(posix_timestamp).replace(tzinfo=pytz.utc)

# convert it to tz
tz = pytz.timezone('America/New_York')
dt = utc_dt.astimezone(tz)

# print it
print(dt.strftime('%Y-%m-%d %H:%M:%S %Z%z'))

Or a simpler alternative is to construct from the timestamp directly:

from datetime import datetime
import pytz

# get time in tz
tz = pytz.timezone('America/New_York')
dt = datetime.fromtimestamp(posix_timestamp, tz)
# print it
print(dt.strftime('%Y-%m-%d %H:%M:%S %Z%z'))

It converts from UTC implicitly in this case.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share

2.1m questions

2.1m answers

62 comments

56.6k users

...