Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: How to convert string into datetime [duplicate]

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.

like image 235
Sunny Avatar asked Oct 01 '12 11:10

Sunny


People also ask

How do I convert a string to a date?

Using strptime() , date and time in string format can be converted to datetime type. The first parameter is the string and the second is the date time format specifier. One advantage of converting to date format is one can select the month or date or time individually.

What is Strftime and Strptime in Python?

strptime is short for "parse time" where strftime is for "formatting time". That is, strptime is the opposite of strftime though they use, conveniently, the same formatting specification.


2 Answers

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.

like image 79
Pierre GM Avatar answered Oct 24 '22 16:10

Pierre GM


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

like image 37
Antonio Beamud Avatar answered Oct 24 '22 17:10

Antonio Beamud