On Windows, how do I convert timestamps before 1970 to something manageable?

Summary: โ€œnegativeโ€ timestamps on a Mac work fine, but on Windows I can't convert them to something useful.

More: I can have a file in Windows, the modification time of which, for example, 1904:

$ ls -l peter.txt
-rw-r--r--    1 sync     Administ        1 Jan  1  1904 peter.txt

In python:

>>> import os
>>> ss = os.stat('peter.txt')
>>> ss.st_mtime
-2082816000.0

Great. But I can't figure out how to turn this negative mark into a date / time string. On Mac, this code works fine.

>>> datetime.fromtimestamp(-2082816000)
datetime.datetime(1904, 1, 1, 0, 0)

And from here I can do whatever I want in terms of formatting.

But on Windows this fails:

>>> datetime.fromtimestamp(-2082816000)
Traceback (most recent call last):    
  File "<stdin>", line 1, in <module>
ValueError: timestamp out of range for platform localtime()/gmtime() function

And try something else that I can think of failure:

>>> time.gmtime(-2082816000)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: (22, 'Invalid argument')

the wonderful python-dateutil package does not seem to have this feature. I looked though time, calendar and datetime module. Any help?

+4
2
>>> datetime.datetime(1970, 1, 1) + datetime.timedelta(seconds=-2082816000)
datetime.datetime(1904, 1, 1, 8, 0)
+9

Ignacio, datetime:

def convert_timestamp_to_datetime(timestamp):
    import datetime as dt
    if timestamp >=0:
        return dt.datetime.fromtimestamp(timestamp)
    else:
        return dt.datetime(1970, 1, 1) + dt.timedelta(seconds=int(timestamp))
+1

Source: https://habr.com/ru/post/1529316/


All Articles