[Tutor] datetime substraction

Danny Yoo dyoo at hashcollision.org
Tue Aug 26 18:55:41 CEST 2014


>
> I have written a script, however I'm not able to get the date substraction
> math right, getting the following error
> (Searched google and other resources too).
>
> Traceback (most recent call last):
>   File "./rsyslog_check.py", line 22, in <module>
>     difft=cur_time-mt
> TypeError: unsupported operand type(s) for -: 'str' and 'str'


Hi Anirudh,

This error message suggests that 'cur_time' and 'mt' here are not
dates.  Rather, they're strings.  I'd trust the error message and turn
the question from:

    "How do I subtract date subtraction math right?"

to:

    "Why are these values that I expect to be dates actually strings?"

Let's see... oh, you're using the time.ctime() function here:



> mt = time.ctime(os.path.getctime(tfile))
> cur_time = time.ctime()
> difft=int(cur_time-mt)


What is this doing?  Let's check.  We can look at the standard library
documentation:

    https://docs.python.org/2/library/index.html

Searching...  so this code first uses os.path.getctime(), which takes
a file name and returns the number of seconds since the Epoch.

    https://docs.python.org/2/library/os.path.html#os.path.getctime



What's the meaning of time.ctime?

    https://docs.python.org/2/library/time.html#time.ctime

Ok, from reading time.ctime(), I think you should not be using this
function.  It takes the number of seconds since the Epoch, and formats
it as a nice string for people to read in their local time zone.  So
it's almost useless for doing any mechanical calculations.  To put it
in perspective, it's as if you are trying to do arithmetic with roman
numerals.  Don't do that.


As Stephen points out, you've got the two dates in terms of seconds
since the Epoch, so you might as well just subtract to get the number
of seconds altogether.


If you truly want to treat dates as algebraic objects, consider the
datetime library.

    https://docs.python.org/2/library/datetime.html

You can use the datetime.fromtimestamp() function to take the seconds
since the Epoch and transform them into datetime objects:

    https://docs.python.org/2/library/datetime.html#datetime.datetime.fromtimestamp


More information about the Tutor mailing list