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.
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.
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.
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.
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"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)
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With