Converting a string to a datetime
Need to convert a string to a datetime
object in Python?
You need the strptime
class method.
That’s the easy part.
The hard part is figuring out which format string you need to specify to parse your date string properly.
Parsing strings into datetime
objects ➡️
Here’s an example of the strptime
class method in action:
>>> from datetime import datetime
>>> datetime.strptime("Jun 1 2005 1:33PM", "%b %d %Y %I:%M%p")
datetime.datetime(2005, 6, 1, 13, 33)
Note that strptime
is a class method: we’re calling it on the datetime
class (not an instance of the class).
The strptime
formatting directives 📑
Those single letter %
codes above are special format codes that Python borrowed from the C programming language.
Instead of looking at individual format codes, let’s make a cheat sheet of common date formats:
Format Description | Format String | Example Date String |
---|---|---|
RFC 2822 | %a, %d %b %Y %H:%M:%S |
"Sun, 20 Jul 1969 20:17:40" |
Timestamp | %Y-%m-%d %H:%M:%S |
"1969-07-20 20:17:40" |
ISO 8601 Extended | %Y-%m-%dT%H:%M:%S%z |
"1969-07-20T20:17:40" |
ISO 8601 Extended, no timezone | %Y-%m-%dT%H:%M:%S |
"1969-07-20T20:17:40" |
American Date & Time | %m/%d/%Y %I:%M:%S %p |
"07/20/1969 08:17:40 PM" |
European Date & Time | %d/%m/%Y %H:%M:%S |
"20/07/1969 20:17:40" |
Hyphenated Name with Time | %d-%b-%Y %H:%M |
"20-Jul-1969 20:17" |
ISO 8601 Basic | %Y%m%dT%H%M%SZ |
"19690720T201740Z" |
RFC 3339 with offset | %Y-%m-%d %H:%M:%S%z |
"1969-07-20 20:17:40" |
RFC 3339 in UTC | %Y-%m-%d %H:%M:%SZ |
"1969-07-20 20:17:40Z" |
RFC 2822, no seconds | %a, %d %b %Y %H:%M |
"Sun, 20 Jul 1969 20:17" |
Timestamp, no seconds | %Y-%m-%d %H:%M |
"1969-07-20 20:17" |
American, secondless | %m/%d/%Y %I:%M %p |
"07/20/1969 08:17 PM" |
European, secondless | %d/%m/%Y %H:%M |
"20/07/1969 20:17" |
Short Date | %m/%d/%y |
"07/20/69" |
Year First Date | %Y-%m-%d |
"1969-07-20" |
Long Date | %B %d, %Y |
"July 20, 1969" |
Date with Month Name | %d %b %Y |
"20 Jul 1969" |
PostgreSQL Timestamp | %Y-%m-%d %H:%M:%S.%f |
"1969-07-20 20:17:40.000000" |
Year and Day of Year | %Y-%j |
"1969-201" |
You can find all the datetime
formatting codes in the Python documentation and you can find a slightly more readable cheat sheet table for these codes at strftime.org.
Unless you’re attempting to understand individual %
letter codes, I’d instead use the pym.dev/strptime noted below.
Just parse my string please! ⚡
Have a date string and want to find the format string needed to parse it?
You don’t need to check that table above.
Use this strptime tool instead!
strptime for me
That tool will help you identify the format to use for your strings.
If the date strings you encounter tend to differ, you’ll need a more complex approach.
Look into the python-dateutil package’s dateutil.parser.parse
function (examples).
What time is it? It’s “string parse time” ⏱️
The strptime
method is strangely named.
Some Python programmers pronounce it “sturp time” or “strip time” for short.
I sometimes say “stir pee time” because it hints that there are three separate parts to that name.
That name stands for “string parse time” (str
–p
–time
).
We’ll also see strftime
in a moment, which stands for “string format time” (str
–f
–time
).
Converting a datetime
into a string ⬅️
The datetime
class has a strptime
method for parsing strings into datetime
objects.
What if you need to convert datetime
objects back into strings?
You could use the built-in str
function:
>>> from datetime import datetime
>>> moment = datetime(2046, 10, 31, 15, 46, 10, 736926)
>>> str(moment)
'2046-10-31 15:46:10.736926'
But what if we want our date shown in a different format?
strptime
parses and strftime
formats 🔄
The strftime
method does the opposite of strptime
: it converts datetime
objects to strings, allowing us to specify the format we’d like to use during that conversion.
>>> moment.strftime("%a, %d %b %Y %H:%M:%S")
'Wed, 31 Oct 2046 15:46:10'
However, as noted in the next section, I usually prefer to use f-strings to format datetime
objects instead.
f-strings for datetime
formatting ✨
You can also format datetime
objects with f-strings in Python because datetime
objects support the same C-style format codes within f-string format specifiers:
>>> f"{moment:%m/%d/%Y %I:%M %p}"
'10/31/2046 03:46 PM'
I usually prefer to reach for f-strings when formatting datetime
objects because it’s a bit shorten than the alternative.
Compare this f-string:
>>> f"{moment:%B %d, %Y}"
'October 31, 2046'
To this slightly more verbose strftime
method call:
>>> moment.strftime("%B %d, %Y")
'October 31, 2046'
strptime
for date
and time
objects? 🤔
Python’s datetime
module has date
and time
classes in addition to the datetime
class.
>>> import datetime
>>> full = datetime.datetime(2046, 10, 31, 15, 46, 10)
>>> date = datetime.date(2046, 10, 31)
>>> time = datetime.time(15, 46, 10)
The strftime
method exists on all 3:
>>> full.strftime("%d-%b-%Y %H:%M")
'31-Oct-2046 15:46'
>>> date.strftime("%d %b %Y")
'31 Oct 2046'
>>> time.strftime("%I:%M %p")
'03:46 PM'
And f-string formatting works on all 3 also:
>>> f"It's at precisely {full:%d-%b-%Y %H:%M}."
"It's at precisely 31-Oct-2046 15:46."
>>> f"It's on {date:%d %b %Y}."
"It's on 31 Oct 2046."
>>> f"It's daily at {time:%I:%M %p}."
"It's daily at 03:46 PM."
But the strptime
method only exists on the datetime
class.
>>> from datetime import datetime
>>> string = "31-Oct-2046 15:46"
>>> parsed = datetime.strptime(string, "%d-%b-%Y %H:%M")
>>> parsed
datetime.datetime(2046, 10, 31, 15, 46)
If you need to parse a date string or a time string, you can use the datetime
class’s strptime
method and then convert the resulting datetime
object into a date
or time
string using the date
and time
methods:
>>> from datetime import datetime
>>> date_string = "31-Oct-2046"
>>> time_string = "1:45pm"
>>> datetime.strptime(date_string, "%d-%b-%Y").date()
datetime.date(2046, 10, 31)
>>> datetime.strptime(time_string, "%I:%M%p").time()
datetime.time(13, 45)
Parse with str
–p
–time
, format with str
–f
–time
📝
You can use the datetime.datetime.strptime
class method for parsing a date/time string into a datetime.datetime
object.
You can use the strftime
method on a datetime.datetime
object to format it into a date string.
However, I usually prefer to use f-strings my dates and times.
To remember that you need strptime
for parsing instead of strftime
, remember that it’s “string parse time” and “string format time“.
Also don’t forget that the next time you need to figure out which datetime
format you need, use the strptime tool at https://pym.dev/strptime!
Get strptime help