Python: how to convert a string to datetime

Possible duplicate:
Convert string to datetime

I am parsing an XML file that gives me time in the corresponding isoform:

tc1 = 2012-09-28T16:41:12.9976565
tc2 = 2012-09-28T23:57:44.6636597

But it is treated as a string when I extract this from an XML file. I have two such time values, and I need to make a difference between them to find delta. But since this is a string, I cannot directly do tc2-tc1. But since they are already in isoformat for datetime, how can I get python to recognize it as datetime?

thank.

+5
source share
3 answers

Use the method datetime.strptime:

import datetime
datetime.datetime.strptime(your_string, "%Y-%m-%dT%H:%M:%S.%f")

. , [0,999999], , a ValueError ( 1/10us): , .

+22

datetime .

td = datetime.strptime('2012-09-28T16:41:12.997656', '%Y-%m-%dT%H:%M:%S.%f') - 
     datetime.strptime('2012-09-28T23:57:44.663659', '%Y-%m-%dT%H:%M:%S.%f')
print td
# => datetime.timedelta(-1, 60208, 333997)

: %f . .

+4

You can use the python-dateutil functionparse() more flexible than strptime. Hope this helps you.

+4
source

All Articles