ARTICLE AD BOX
Introduction
The Python datetime and clip modules immoderate spot a strptime() group method to personification strings to objects.
In this article, you’ll usage strptime() to personification 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 nan datetime.strptime() method is:
datetime.strptime(date_string, format)
The datetime.strptime() method returns a datetime entity that matches nan date_string parsed by nan format. Both arguments are required and must beryllium strings.
For specifications astir nan format directives utilized successful datetime.strptime(), mention to nan strftime() and strptime() Format Codes successful nan Python documentation.
Convert String to datetime.datetime() Object Example
The pursuing illustration converts a time and clip drawstring into a datetime.datetime() object, and prints nan group punishment and worthy of nan 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:26
You tin too mention this tutorial connected utilizing str() and repr() functions successful python.
Convert String to datetime.date() Object Example
The pursuing illustration converts a time drawstring into a datetime.date() object, and prints nan group type and worthy of nan 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-19
Convert String to datetime.time() Object Example
The pursuing illustration converts a clip drawstring into a datetime.time() object, and prints nan group type and worthy of nan 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:26
Convert String to datetime.datetime() Object pinch Locale Example
The pursuing illustration converts a German locale time drawstring into a datetime.datetime() object, and prints nan group type and worthy of nan 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:00
Note that nan resulting entity doesn’t spot nan weekday punishment from nan input drawstring because a datetime.datetime() entity includes nan weekday only arsenic a decimal number.
Converting a String to a struct_time() Object Using time.strptime()
The syntax for nan time.strptime() method is:
time.strptime(time_string[, format])
The time.strptime() method returns a time.struct_time() entity that matches nan time_string parsed by nan format. The time_string is required and immoderate arguments must beryllium strings. If format is not provided, nan default is:
'%a %b %d %H:%M:%S %Y'
This corresponds to nan format returned by nan ctime() function.
The format directives are nan aforesaid for time.strptime() and time.strftime(). Learn overmuch astir nan format directives for nan clip module successful nan 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 nan format argument, and prints nan worthy of nan 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 nan format provided:") print(time_obj)
The output is:
A time.struct_time entity that uses nan 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 nan output, erstwhile you personification a drawstring into a time.struct_time() object, nan strptime() method uses placeholder values for immoderate format directives that aren’t defined successful nan format argument.
Convert String to struct_time() Object Using Default Format Example
If you don’t proviso a format connection erstwhile you personification a clip drawstring into a time.struct_time() object, past nan default format is utilized and an correction occurs if nan input drawstring does not precisely lucifer nan 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 connection provided, and prints nan worthy of nan 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 nan default format:") print(time_obj_default)
The output is:
A time.struct_time entity that uses nan 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 nan output, erstwhile you personification a drawstring into a time.struct_time() object, nan strptime() method uses placeholder values for immoderate format directives that aren’t defined successful nan format connection aliases by nan default format if nary format is provided.
Troubleshooting strptime() Errors
If nan input drawstring can’t beryllium parsed by strptime() utilizing nan provided format, past a ValueError is raised. You tin usage nan effort artifact to proceedings for parsing errors, connected pinch nan isolated from artifact to group nan results. The ValueError messages that you get erstwhile you usage nan strptime() method intelligibly explicate nan guidelines causes of nan parsing errors. The pursuing illustration demonstrates immoderate communal errors, specified arsenic different accusation 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 accusation remains: 13:55:26 ValueError 2: time accusation '99::55::26' does not lucifer format '%H::%M::%S'
Conclusion
In this tutorial, you converted time and clip strings into datetime and clip objects utilizing Python. Continue your learning pinch overmuch Python tutorials.
FAQs
1. How to personification Python time drawstring mm dd yyyy to datetime?
To personification a time drawstring successful nan mm dd yyyy format to a datetime entity successful Python, you tin usage nan datetime.strptime method from nan 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:00
2. How to personification a drawstring to time successful mm dd yyyy format?
You tin parse nan drawstring into a datetime entity and past extract conscionable nan 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 2024
3. How to personification a drawstring to yyyy-mm-dd format successful Python?
First, parse nan drawstring into a datetime entity and past format it into nan 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-25
4. How to personification datetime to dd, mm, yyyy format successful Python?
You tin usage nan 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, 2024
5. How to personification 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:00
6. What is nan regular look for time format mm dd yyyy successful Python?
A regular look to lucifer a time drawstring successful nan 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 time format") else: print("Invalid time 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.