13

Possible Duplicate:
Converting string into datetime

I am parsing an XML file that gives me the time in the respective isoformat:

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

But it is being treated as a string when I retrieve this from the XML file. I have two such time values and i need to do a diff between the two so as to find delta. But since it is a string I can not directly do tc2-tc1. But since they are already in isoformat for datetime, how do i get python to recognize it as datetime?

thanks.

1
  • 2
    Have you looked at datetime.strptime()? Commented Oct 1, 2012 at 11:48

3 Answers 3

31

Use the datetime.strptime method:

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

The link provided presents the different format directives. Note that the microseconds are limited to the range [0,999999], meaning that a ValueError will be raised with your example (you're using 1/10us): you need to truncate your string to drop the final character.

Sign up to request clarification or add additional context in comments.

2 Comments

quick add on question. once i have the values in datetime, how do i get the time difference?
datetime_object_2-datetime_object_1 will give you a datetime.timedelta object.
5

You can use the python-dateutil parse() function, it's more flexible than strptime. Hope this help you.

1 Comment

4

Use the datetime module.

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)

There is only one small problem: Your microseconds are one digit to long for %f to handle. So I've removed the last digits from your input strings.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.