Anastasios Andronidis
Anastasios Andronidis

Reputation: 6720

Python datetime weird behavior

I trying this in Python. What is the difference of those:

>>> a = datetime.fromtimestamp(1373576406)
>>> a.replace(tzinfo=tzutc())
datetime.datetime(2013, 7, 12, 0, 0, 6, tzinfo=tzutc())
>>> a.strftime('%s')
'1373576406'

and

>>> datetime.fromtimestamp(1373576406).replace(tzinfo=tzutc()).strftime('%s')
'1373580006'

I don't really understand why this is happening. Shouldn't both timestamps be equal?

I tried these in both Python 3.3.2 and Python 2.7.1

Upvotes: 1

Views: 129

Answers (1)

Wessie
Wessie

Reputation: 3510

datetime.replace returns a new datetime instance.

In your first example you are ignoring the return value of datetime.replace and are then doing datetime.strftime on your old datetime instance.

This causes the inequality you are experiencing.

To make both examples equal you would have to edit the verbose one to look like:

>>> a = datetime.fromtimestamp(1373576406)
>>> a = a.replace(tzinfo=tzutc())
>>> a.strftime('%s')
'1373576406

Upvotes: 2

Related Questions