datetime.strptime parses an input string in the user-specified format into a timezone-naive datetime object:
>>> from datetime import datetime
>>> datetime.strptime('Jun 1 2005 1:33PM', '%b %d %Y %I:%M%p')
datetime.datetime(2005, 6, 1, 13, 33)
To obtain a date object using an existing datetime object, convert it using .date():
>>> datetime.strptime('Jun 1 2005', '%b %d %Y').date()
date(2005, 6, 1)
Links:
strptimedocs: Python 2, Python 3strptime/strftimeformat string docs: Python 2, Python 3strftime.org format string cheatsheet
Notes:
strptime= "string parse time"strftime= "string format time"
datetime.strptime parses an input string in the user-specified format into a timezone-naive datetime object:
>>> from datetime import datetime
>>> datetime.strptime('Jun 1 2005 1:33PM', '%b %d %Y %I:%M%p')
datetime.datetime(2005, 6, 1, 13, 33)
To obtain a date object using an existing datetime object, convert it using .date():
>>> datetime.strptime('Jun 1 2005', '%b %d %Y').date()
date(2005, 6, 1)
Links:
strptimedocs: Python 2, Python 3strptime/strftimeformat string docs: Python 2, Python 3strftime.org format string cheatsheet
Notes:
strptime= "string parse time"strftime= "string format time"
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 and is more convenient than strptime since it usually guesses the correct format. It is also very useful for writing tests, where readability is more important than performance.
Install it with:
pip install python-dateutil
Videos
Hi.
Consider this text string: 2021-01-01 01:01:00 UTC.
What's the best way of parsing this into a date object in Python 3? I could remove the "UTC" from the text, and then use something like datetime.strptime(date_string, format), but isn't there an easier way, like doesn't Python already have support for parseing strings like these?
» pip install DateTime