Python 3: timestamp to datetime: where does this additional hour come from?

Posted by Beau Martínez on Stack Overflow See other posts from Stack Overflow or by Beau Martínez
Published on 2010-04-05T23:52:55Z Indexed on 2010/04/06 0:13 UTC
Read the original article Hit count: 489

Filed under:
|

I'm using the following functions:

# The epoch used in the datetime API.
EPOCH = datetime.datetime.fromtimestamp(0)

def timedelta_to_seconds(delta):
    seconds = (delta.microseconds * 1e6) + delta.seconds + (delta.days * 86400)
    seconds = abs(seconds)

    return seconds

def datetime_to_timestamp(date, epoch=EPOCH):
    # Ensure we deal with `datetime`s.
    date = datetime.datetime.fromordinal(date.toordinal())
    epoch = datetime.datetime.fromordinal(epoch.toordinal())

    timedelta = date - epoch
    timestamp = timedelta_to_seconds(timedelta)

    return timestamp

def timestamp_to_datetime(timestamp, epoch=EPOCH):
    # Ensure we deal with a `datetime`.
    epoch = datetime.datetime.fromordinal(epoch.toordinal())

    epoch_difference = timedelta_to_seconds(epoch - EPOCH)
    adjusted_timestamp = timestamp - epoch_difference

    date = datetime.datetime.fromtimestamp(adjusted_timestamp)

    return date

And using them with the passed code:

twenty = datetime.datetime(2010, 4, 4)

print(twenty)
print(datetime_to_timestamp(twenty))
print(timestamp_to_datetime(datetime_to_timestamp(twenty)))

And getting the following results:

2010-04-04 00:00:00
1270339200.0
2010-04-04 01:00:00

For some reason, I'm getting an additional hour added in the last call, despite my code having, as far as I can see, no flaws.

Where is this additional hour coming from?

© Stack Overflow or respective owner

Related posts about python-3.x

Related posts about datetime