Emmanuel Arias
Emmanuel Arias

Reputation: 484

TimeStamp to date Python

I am trying to convert a timestamp (that I don't know how it is convert) to datetime.

I have this input: 1217099350.0

If I write this on Libreoffice calc (1217099350.0/86400) + 29226 and format the cell to date time. I have a correct output:

31/07/2018 19:09:10

But if I make this on python:

tt = 1217099350.0
tt2 = (tt / 86400.) + 29226.
tt3 = datetime.fromtimestamp(tt2).strftime("%Y-%M-%d %H:%m:%S"
print(tt3)

I have the next output:

1970-01-01 09:01:52

What is the problem on my code?

Thanks! Regards!

Upvotes: 3

Views: 9436

Answers (2)

Jeffrey Harper
Jeffrey Harper

Reputation: 888

Emmanuel,

Changing the Epoch in Python would likely be a lot of work. It might be easier to do some math on your LibreOffice timestamps to convert them to Posix timestamps before calling datetime.utfromtimestamp.

This won't work, however, if you use timestamps before Jan. 1, 1970.

from datetime import datetime
tt = 1217099350.0
tt2 = (tt / 86400.) + 29226.
# At this point tt2 has days since the LibreOffice Epoch.  Below, it
# is converted to seconds since Posix epoch.
tt3 = tt2 - 25569.  # There are 25569 days between LibreOffice and Posix epoch
tt4 = tt3 * 86400.  # Convert timestamp from days to seconds
tt5 = datetime.utcfromtimestamp(tt4).strftime("%Y-%m-%d %H:%M:%S")
print(tt5)

2018-07-31 19:09:10

Upvotes: 7

Jeffrey Harper
Jeffrey Harper

Reputation: 888

It appears that LibreOffice epoch is not the same as the Posix epoch. I found this article that might be helpful.

https://syslog.me/2012/08/28/dates-from-unix-timestamps-in-openoffice-libreoffice/

The Posix epoch is midnight Jan. 1, 1970 UTC.

>>> datetime.utcfromtimestamp(0).strftime("%Y-%m-%d %H:%M:%S")
'1970-01-01 00:00:00'

The LibreOffice epoch is Dec. 30, 1899.

The divide by 86400 suggests that you are trying to convert seconds to days. However, the datetime.fromtimestamp function in Python expects a timestamp in seconds.

Also, in your call to strftime you reversed months and minutes. %M gives minutes and %m gives months.

Finally, you may want to use utcfromtimestamp instead of fromttimestamp to avoid time-zone issues.

Upvotes: 3

Related Questions