Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

datetime from string in Python, best-guessing string format

The function to get a datetime from a string, datetime.strptime(date_string, format) requires a string format as the second argument. Is there a way to build a datetime from a string without without knowing the exact format, and having Python best-guess it?

like image 908
Yarin Avatar asked Feb 29 '12 22:02

Yarin


2 Answers

Use the dateutil library.

I was already using dateutil as an indispensable lib for handling timezones
(See Convert UTC datetime string to local datetime and How do I convert local time to UTC in Python?)

And I've just realized it has date parsing support:

import dateutil.parser yourdate = dateutil.parser.parse(datestring) 

(See also How do I translate a ISO 8601 datetime string into a Python datetime object?)

like image 72
Yarin Avatar answered Oct 19 '22 02:10

Yarin


Can get away with a simple function if only checking against dates.

def get_date(s_date):     date_patterns = ["%d-%m-%Y", "%Y-%m-%d"]      for pattern in date_patterns:         try:             return datetime.datetime.strptime(s_date, pattern).date()         except:             pass      print "Date is not in expected format: %s" %(s_date)     sys.exit(0) 
like image 31
Sandeep Avatar answered Oct 19 '22 02:10

Sandeep