Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting string into datetime

I've got a huge list of date-times like this as strings:

Jun 1 2005  1:33PM Aug 28 1999 12:00AM 

I'm going to be shoving these back into proper datetime fields in a database so I need to magic them into real datetime objects.

This is going through Django's ORM so I can't use SQL to do the conversion on insert.

like image 337
Oli Avatar asked Jan 21 '09 18:01

Oli


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.

How do I convert a string to a date in SQL?

Convert string to date using CAST() function In this syntax, the string can be any DATE value that is convertible to a date. The CAST() function returns a DATE value if it successfully converts the string to date.

Can we convert string to date in Java?

By default, Java dates are in the ISO-8601 format, so if we have any string which represents a date and time in this format, then we can use the parse() API of these classes directly.


2 Answers

datetime.strptime is the main routine for parsing strings into datetimes. It can handle all sorts of formats, with the format determined by a format string you give it:

from datetime import datetime  datetime_object = datetime.strptime('Jun 1 2005  1:33PM', '%b %d %Y %I:%M%p') 

The resulting datetime object is timezone-naive.

Links:

  • Python documentation for strptime: Python 2, Python 3

  • Python documentation for strptime/strftime format strings: Python 2, Python 3

  • strftime.org is also a really nice reference for strftime

Notes:

  • strptime = "string parse time"
  • strftime = "string format time"
  • Pronounce it out loud today & you won't have to search for it again in 6 months.

Also, as seen in a comment made by @Izkata, if you want a date instead of a datetime, going through datetime handles it nicely: datetime.strptime('Jun 1 2005', '%b %d %Y').date() == date(2005, 6, 1)

like image 145
Patrick Harrington Avatar answered Sep 22 '22 10:09

Patrick Harrington


Use the third party dateutil library:

from dateutil import parser parser.parse("Aug 28 1999 12:00AM")  # datetime.datetime(1999, 8, 28, 0, 0) 

It can handle most date formats, including the one you need to parse. It's more convenient than strptime as it can guess the correct format most of the time.

It's very useful for writing tests, where readability is more important than performance.

You can install it with:

pip install python-dateutil 
like image 32
Simon Willison Avatar answered Sep 18 '22 10:09

Simon Willison