0

I am new to Python, I have been asked to write a script to display the time difference. I get these times using shell scripts and are stored in some variables H1 and H2.

I was wondering if i could use datetime.datetime in Python to calculate the difference the below code is not possible

H1 = "2009,12,22,22,22"
H2 = "2009,12,22,20,22"
g =datetime.datetime(H1) - datetime.datetime(H2)

how could i pass variables or if it is not possible ?

2
Contributors
1
Reply
2
Views
8 Years
Discussion Span
Last Post by BearofNH
0

The datetime object takes a series of integers, not a single string:

>>> t1 = datetime.datetime(2009,12,22,22,22)
>>> t2 = datetime.datetime(2009,12,22,20,22)
>>> (t1-t2).days
0
>>> (t1-t2).seconds
7200
>>>

The difference between two datetimes is a timedelta, an object containing days, seconds and microseconds.

If you really have to work with strings then you can coerce them as ff:

>>> H1 = "2009,12,22,22,22"
>>> t1 = datetime.datetime(*tuple([int(x) for x in H1.split(',')]))
>>> t1
datetime.datetime(2009, 12, 22, 22, 22)
>>>
This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.