Problem saving datetime to file and reading it back for a calculation

Cameron Simpson cs at cskk.id.au
Sat Oct 10 21:50:11 EDT 2020


On 10Oct2020 18:17, Steve <Gronicus at SGA.Ninja> wrote:
>I would like to use the line:
>HoursDiff = int((d2-d1).total_seconds()/3600)
>to determine the difference in hours between two timedate entries.
>
>The variable d2 is from datetime.now()
>and d1 is read from a text file.
>
>I can save d2 to the file only if I convert it to string and, at a later
>date, it gets read back in as d1 as string.

That is the nature of text files.

>The variable d1 as string will
>not work in the HoursDiff statement.

Because it is a string.

Peter has described a way to transcribe a datetime in an arbitrary string 
format and back. Note that his example formats are "naive" - they don't know 
what you timezone is, and you want that if that ever varies (not just 
datetimes in contexts from different places, but also at different times of 
the year if you run different summer and winter times, particularly 
troublesome around the transition from one to the other).

>To me, it looks like a problem in formatting.
>How do I fix this?

Personally I strongly dislike using datetimes for computation or as the 
basis for time record keeping, essentially because of the timezone issue 
but also because the human calendar is a complex disaster of illfitting 
units (days in a year? variable; days in a month? variable; that table 
of days per unit? variable depending on your time in history).

Instead, I always try to work in POSIX timestamps, an absolute number of 
seconds since midnight, 1 January 1970 GMT. You can always do arithmetic 
directly between these in seconds, then convert for presentation 
purposes whenever.

Because you're now working in seconds directly, you go:

    HoursDiff = int((t2-t1)/3600)

or:

    HoursDiff = (t2-t1) // 3600

When you first collect your datetime, convert it to a POSIX timestamp 
immediately. If you're _starting_ from datetime.now(), do not do that! Just 
start with time.time() and no conversion is needed at all.

Just _present_ in datetime formats if you need to. DO NOT try to work 
with them as your basic type - they are a source of pitfalls.

As far as storing timestamps in a file, they're ints or floats; just 
write them out.

Cheers,
Cameron Simpson <cs at cskk.id.au>


More information about the Python-list mailing list