Introduction
The Python datetime and clip modules some see a strptime() people method to person strings to objects.
In this article, you’ll usage strptime() to person strings into datetime and struct_time() objects.
Deploy your Python applications from GitHub utilizing DigitalOcean App Platform. Let DigitalOcean attraction connected scaling your app.
Converting a String to a datetime entity utilizing datetime.strptime()
The syntax for the datetime.strptime() method is:
datetime.strptime(date_string, format)The datetime.strptime() method returns a datetime entity that matches the date_string parsed by the format. Both arguments are required and must beryllium strings.
For specifications astir the format directives utilized successful datetime.strptime(), mention to the strftime() and strptime() Format Codes successful the Python documentation.
Convert String to datetime.datetime() Object Example
The pursuing illustration converts a day and clip drawstring into a datetime.datetime() object, and prints the people sanction and worth of the resulting object:
from datetime import datetime datetime_str = '09/19/22 13:55:26' datetime_object = datetime.strptime(datetime_str, '%m/%d/%y %H:%M:%S') print(type(datetime_object)) print(datetime_object)The output is:
<class 'datetime.datetime'> 2022-09-19 13:55:26You tin besides mention this tutorial connected utilizing str() and repr() functions successful python.
Convert String to datetime.date() Object Example
The pursuing illustration converts a day drawstring into a datetime.date() object, and prints the people type and worth of the resulting object:
from datetime import datetime date_str = '09-19-2022' date_object = datetime.strptime(date_str, '%m-%d-%Y').date() print(type(date_object)) print(date_object)The output is:
<class 'datetime.date'> 2022-09-19Convert String to datetime.time() Object Example
The pursuing illustration converts a clip drawstring into a datetime.time() object, and prints the people type and worth of the resulting object:
from datetime import datetime time_str = '13::55::26' time_object = datetime.strptime(time_str, '%H::%M::%S').time() print(type(time_object)) print(time_object)The output is:
<class 'datetime.time'> 13:55:26Convert String to datetime.datetime() Object pinch Locale Example
The pursuing illustration converts a German locale day drawstring into a datetime.datetime() object, and prints the people type and worth of the resulting object:
from datetime import datetime import locale locale.setlocale(locale.LC_ALL, 'de_DE') date_str_de_DE = '16-Dezember-2022 Freitag' datetime_object = datetime.strptime(date_str_de_DE, '%d-%B-%Y %A') print(type(datetime_object)) print(datetime_object)The output is:
<class 'datetime.datetime'> 2022-12-16 00:00:00Note that the resulting entity doesn’t see the weekday sanction from the input drawstring because a datetime.datetime() entity includes the weekday only arsenic a decimal number.
Converting a String to a struct_time() Object Using time.strptime()
The syntax for the time.strptime() method is:
time.strptime(time_string[, format])The time.strptime() method returns a time.struct_time() entity that matches the time_string parsed by the format. The time_string is required and some arguments must beryllium strings. If format is not provided, the default is:
'%a %b %d %H:%M:%S %Y'This corresponds to the format returned by the ctime() function.
The format directives are the aforesaid for time.strptime() and time.strftime(). Learn much astir the format directives for the clip module successful the Python documentation.
Convert String to struct_time() Object With Format Provided Example
The pursuing illustration converts a clip drawstring into a time.struct_time() entity by providing the format argument, and prints the worth of the resulting object:
import time time_str = '11::33::54' time_obj = time.strptime(time_str, '%H::%M::%S') print("A time.struct_time entity that uses the format provided:") print(time_obj)The output is:
A time.struct_time entity that uses the format provided: time.struct_time(tm_year=1900, tm_mon=1, tm_mday=1, tm_hour=11, tm_min=33, tm_sec=54, tm_wday=0, tm_yday=1, tm_isdst=-1)As shown successful the output, erstwhile you person a drawstring into a time.struct_time() object, the strptime() method uses placeholder values for immoderate format directives that aren’t defined successful the format argument.
Convert String to struct_time() Object Using Default Format Example
If you don’t supply a format statement erstwhile you person a clip drawstring into a time.struct_time() object, past the default format is utilized and an correction occurs if the input drawstring does not precisely lucifer the default format of:
'%a %b %d %H:%M:%S %Y'The pursuing illustration converts a clip drawstring into a time.struct_time() entity pinch nary format statement provided, and prints the worth of the resulting object:
import time time_str_default = 'Mon Dec 12 14:55:02 2022' time_obj_default = time.strptime(time_str_default) print("A time.struct_time entity that uses the default format:") print(time_obj_default)The output is:
A time.struct_time entity that uses the default format: time.struct_time(tm_year=2022, tm_mon=12, tm_mday=12, tm_hour=14, tm_min=55, tm_sec=2, tm_wday=0, tm_yday=346, tm_isdst=-1)As shown successful the output, erstwhile you person a drawstring into a time.struct_time() object, the strptime() method uses placeholder values for immoderate format directives that aren’t defined successful the format statement aliases by the default format if nary format is provided.
Troubleshooting strptime() Errors
If the input drawstring can’t beryllium parsed by strptime() utilizing the provided format, past a ValueError is raised. You tin usage the effort artifact to trial for parsing errors, on pinch the isolated from artifact to people the results. The ValueError messages that you get erstwhile you usage the strptime() method intelligibly explicate the guidelines causes of the parsing errors. The pursuing illustration demonstrates immoderate communal errors, specified arsenic other information and a format mismatch:
from datetime import datetime import time datetime_str = '09/19/18 13:55:26' try: datetime_object = datetime.strptime(datetime_str, '%m/%d/%y') except ValueError as ve1: print('ValueError 1:', ve1) time_str = '99::55::26' try: time_object = time.strptime(time_str, '%H::%M::%S') except ValueError as ve2: print('ValueError 2:', ve2)The output is:
ValueError 1: unconverted information remains: 13:55:26 ValueError 2: time information '99::55::26' does not lucifer format '%H::%M::%S'Conclusion
In this tutorial, you converted day and clip strings into datetime and clip objects utilizing Python. Continue your learning pinch much Python tutorials.
FAQs
1. How to person Python day drawstring mm dd yyyy to datetime?
To person a day drawstring successful the mm dd yyyy format to a datetime entity successful Python, you tin usage the datetime.strptime method from the datetime module:
from datetime import datetime date_string = "12 25 2024" date_object = datetime.strptime(date_string, "%m %d %Y") print(date_object)The Output is:
2024-12-25 00:00:002. How to person a drawstring to day successful mm dd yyyy format?
You tin parse the drawstring into a datetime entity and past extract conscionable the date:
from datetime import datetime date_string = "12 25 2024" date_object = datetime.strptime(date_string, "%m %d %Y").date() print(date_object)The output is:
12 25 20243. How to person a drawstring to yyyy-mm-dd format successful Python?
First, parse the drawstring into a datetime entity and past format it into the desired yyyy-mm-dd drawstring format:
from datetime import datetime date_string = "12 25 2024" date_object = datetime.strptime(date_string, "%m %d %Y") formatted_date = date_object.strftime("%Y-%m-%d") print(formatted_date)The output is:
2024-12-254. How to person datetime to dd, mm, yyyy format successful Python?
You tin usage the strftime method to format a datetime entity into a circumstantial drawstring format:
from datetime import datetime date_object = datetime(2024, 12, 25) formatted_date = date_object.strftime("%d, %m, %Y") print(formatted_date)The output is :
25, 12, 20245. How to person a drawstring to datetime successful Python?
The datetime.strptime method tin beryllium utilized to parse a drawstring into a datetime object. For example:
from datetime import datetime date_string = "2024-12-25" date_object = datetime.strptime(date_string, "%Y-%m-%d") print(date_object)The output is:
2024-12-25 00:00:006. What is the regular look for day format mm dd yyyy successful Python?
A regular look to lucifer a day drawstring successful the mm dd yyyy format could look for illustration this:
import re regex = r"^(0[1-9]|1[0-2]) ([0-2][0-9]|3[01]) (\d{4})$" date_string = "12 25 2024" if re.match(regex, date_string): print("Valid day format") else: print("Invalid day format")This regex ensures:
- mm ranges from 01 to 12 (month).
- dd ranges from 01 to 31 (day).
- yyyy is simply a four-digit year.