Get File's Epoch timestamp, convert to DateTime, to string, and then to the identical epoch float with microsecond precision

241 Views Asked by At

I want to take a file's epoch timestamp float (e.g., "1661796943.8816772" from "os.stat(__file__).st_mtime"), and convert that float to what I think is called a DateTime string, and convert that DateTime string back to a float that is identical to the float I started with, i.e. from "os.stat(__file__).st_mtime".

I think my DateTime string has the precision I want (e.g., "2022,08,29,11,15,43,881677"), and I'm able to convert it to a DateTime object:

print(my_DateTime_obj)
>>2022-08-29 11:15:43.881677

But the routine I found to convert the DateTime object to an Epoch float lacks a lot of the precision my original float ("1661796943.8816772") had:

print(time.mktime(DateTime_obj.timetuple()))
>>1661796943.0

I think timetuple() is the problem, but I have not been able to figure it out. Any tips about how to the convert the DateTime object to an Epoch float, without losing what I think is the microsecond precision, would be much appreciated.
I confess I am still a long way from understanding mktime(), timetuple() and what "structured time" really means.

1

There are 1 best solutions below

2
FObersteiner On BEST ANSWER

use the datetime module:

import os
from datetime import datetime, timezone

import numpy as np

# file modification time, seconds since Unix epoch
unix0 = os.stat(__file__).st_mtime

# to datetime object
dt = datetime.fromtimestamp(unix0, tz=timezone.utc)
print(dt.isoformat(timespec="microseconds"))
# e.g.
# 2022-08-30T08:31:32.117021+00:00

# datetime object back to Unix time
unix1 = dt.timestamp()

# assert equal with microsecond precision
assert np.isclose(unix0, unix1, atol=1e-6)

Note: if you don't set tz=timezone.utc, the datetime object will be naive (as opposed to timezone-aware) and resemble local time. The conversion would work correctly nevertheless.