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 ?

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)
>>>
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.