0

I am new to Python and programming in general but I'm willing to learn. I am trying to open a file that just has a time stamp inside of it. I want to take that time in the file and compare it to the now time. I think my issue is I am not converting the incoming string to the right format. Any help would be excellent and help me learn.

-D

`

from datetime import datetime

# get current time
now = datetime.now()
print("Current time: ", now)

filePathLastUpdated = '/Users/dmurray/Desktop/printer folder test/LastUpDated.txt'
lastUpdated = open(filePathLastUpdated, "r")

print("last updated time: ", lastUpdated.read())

if lastUpdated.read() < now:
    print("not up to date")
else:
    print("up to date")`

the text in the file is "2020-05-20 09:51:28.874028"

1 Answers1

0

There is a great date utility package called python-dateutil which provides invaluable help when working with dates. Among other things, it can parse your date into a datetime object which can be compared to others. datetime objects naturally are comparable. Once you have the right type, you're good to go!

import datetime
import dateutil.parser

now = datetime.datetime.now()
not_now = dateutil.parser.parse("2020-05-20 09:51:28.874028")

updated = not_now >= now

Another option is combining strptime with the expected format codes of the "stringed" date to produce a similar datetime object.
But, I highly recommend having python-dateutil as a de-facto package for working with dates.

edd
  • 1,307
  • 10
  • 10