[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

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

On Sat, 10 Oct 2020 18:17:26 -0400, 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.   The variable d1 as string will
> not work in the HoursDiff statement.
> To me, it looks like a problem in formatting.
> How do I fix this?

datetime.datetime.strftime and datetime.datetime.strptime ?

>>> t = datetime.datetime.now()
>>> t.strftime("%Y-%m-%d %H:%M:%S")
'2020-10-10 18:02:33'
>>> b = datetime.datetime.strptime("2020-09-09 12:34:56", "%Y-%m-%d %H:%M:%S")
>>> b.strftime("%Y-%m-%d %H:%M:%S")
'2020-09-09 12:34:56'

To email me, substitute nowhere->runbox, invalid->com.