Report this

What is the reason for this report?

How To Convert a String to a datetime Object in Python

Updated on December 13, 2024
How To Convert a String to a datetime Object in Python

Introduction

The Python datetime and time modules both include a strptime() class method to convert strings to objects.

In this article, you’ll use strptime() to convert strings into datetime and struct_time() objects.

Deploy your Python applications from GitHub using DigitalOcean App Platform. Let DigitalOcean focus on scaling your app.

Converting a String to a datetime object using datetime.strptime()

The syntax for the datetime.strptime() method is:

datetime.strptime(date_string, format)

The datetime.strptime() method returns a datetime object that matches the date_string parsed by the format. Both arguments are required and must be strings.

For details about the format directives used in datetime.strptime(), refer to the strftime() and strptime() Format Codes in the Python documentation.

Convert String to datetime.datetime() Object Example

The following example converts a date and time string into a datetime.datetime() object, and prints the class name and value 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)  # printed in default format

The output is:

<class 'datetime.datetime'>
2022-09-19 13:55:26

You can also refer this tutorial on using str() and repr() functions in python.

Convert String to datetime.date() Object Example

The following example converts a date string into a datetime.date() object, and prints the class type and value 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)  # printed in default format

The output is:

<class 'datetime.date'>
2022-09-19

Convert String to datetime.time() Object Example

The following example converts a time string into a datetime.time() object, and prints the class type and value 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:26

Convert String to datetime.datetime() Object with Locale Example

The following example converts a German locale date string into a datetime.datetime() object, and prints the class type and value 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'  # de_DE locale
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 the resulting object doesn’t include the weekday name from the input string because a datetime.datetime() object includes the weekday only as 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() object that matches the time_string parsed by the format. The time_string is required and both arguments must be 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 same for time.strptime() and time.strftime(). Learn more about the format directives for the time module in the Python documentation.

Convert String to struct_time() Object With Format Provided Example

The following example converts a time string into a time.struct_time() object by providing the format argument, and prints the value 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 object that uses the format provided:")
print(time_obj)

The output is:

A time.struct_time object 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 in the output, when you convert a string into a time.struct_time() object, the strptime() method uses placeholder values for any format directives that aren’t defined in the format argument.

Convert String to struct_time() Object Using Default Format Example

If you don’t provide a format argument when you convert a time string into a time.struct_time() object, then the default format is used and an error occurs if the input string does not exactly match the default format of:

 '%a %b %d %H:%M:%S %Y'

The following example converts a time string into a time.struct_time() object with no format argument provided, and prints the value of the resulting object:

import time

# default format - "%a %b %d %H:%M:%S %Y"
time_str_default = 'Mon Dec 12 14:55:02 2022'
time_obj_default = time.strptime(time_str_default)
print("A time.struct_time object that uses the default format:")
print(time_obj_default)

The output is:

A time.struct_time object 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 in the output, when you convert a string into a time.struct_time() object, the strptime() method uses placeholder values for any format directives that aren’t defined in the format argument or by the default format if no format is provided.

Troubleshooting strptime() Errors

If the input string can’t be parsed by strptime() using the provided format, then a ValueError is raised. You can use the try block to test for parsing errors, along with the except block to print the results. The ValueError messages that you get when you use the strptime() method clearly explain the root causes of the parsing errors. The following example demonstrates some common errors, such as extra data 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 data remains:  13:55:26
ValueError 2: time data '99::55::26' does not match format '%H::%M::%S'

Conclusion

In this tutorial, you converted date and time strings into datetime and time objects using Python. Continue your learning with more Python tutorials.

FAQs

1. How to convert Python date string mm dd yyyy to datetime?

To convert a date string in the mm dd yyyy format to a datetime object in Python, you can use 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:00

2. How to convert a string to date in mm dd yyyy format?

You can parse the string into a datetime object and then extract just 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 2024

3. How to convert a string to yyyy-mm-dd format in Python?

First, parse the string into a datetime object and then format it into the desired yyyy-mm-dd string 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 convert datetime to dd, mm, yyyy format in Python?

You can use the strftime method to format a datetime object into a specific string 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 convert a string to datetime in Python?

The datetime.strptime method can be used to parse a string 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 the regular expression for date format mm dd yyyy in Python?

A regular expression to match a date string in the mm dd yyyy format could look like 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 date format")
else:
    print("Invalid date format")

This regex ensures:

  • mm ranges from 01 to 12 (month).
  • dd ranges from 01 to 31 (day).
  • yyyy is a four-digit year.

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Learn more about our products

About the author(s)

Andrea Anderson
Andrea Anderson
Author
Technical Editor
See author profile
Anish Singh Walia
Anish Singh Walia
Author
Sr Technical Writer
See author profile

Helping Businesses stand out with AI, SEO, & Technical content that drives Impact & Growth | Senior Technical Writer @ DigitalOcean | 2x Medium Top Writers | 2 Million+ monthly views & 34K Subscribers | Ex Cloud Engineer @ AMEX | Ex SRE(DevOps) @ NUTANIX

Still looking for an answer?

Was this helpful?

Hi Pankaj ! I need some help. I have a sample .CSV file from a Finger mark scanner to maintain attendance of employees. Can some one help me with a code to convert, Date, and other two Time columns to Date/Time in Pandas? I get an error. please see the attachment. https://colab.research.google.com/drive/1dnfigKSDoZsXiVIByWojXnkSgAEI6WOr Thank you !!! Indrajith - Sri Lanka 0772 078 441 / Mobile/Wtsapp

- Indrajith

In the datetime module, there is a function “datetime.datetime.today().weekday()”. This function returns the day of the week as an integer, where Monday is 0 and Sunday is 6. Please write a Python program using a for loop to generate and print log entries for the rest of the week starting from today. For example, if today is Wednesday, the program prints “Wednesday entry:”, “Thursday entry:”, “Friday entry:”, and “Saturday entry:” in separate lines. (Hint: the lower end of the range is today’s weekday and the upper end is 5 for Saturday).

- bhaigan

Thank you Sir! Found this arrticle very useful, when converting string data to dates in MongoDB documents!

- Victor Ochieng

Hi what about the day of the month, without 0-padding? 1,2,3,…,10,…30,31? In strftime it would be %-d, but that verbose doesn’t work when using to_datetime (string_to_convert_in_date, format=format_to_use) Any ideas? Thanks

- nono_london

Thank you for the post, very helpful examples

- Leo

Hello, Can you please let me know, how to compare 2 dates with $gte and $lte using python and mongodb ?

- RB

There is a mistake in this article. The ‘y’ in ‘%m/%d/%y’ will be capital. so the format will be ‘%m/%d/%Y’ i faced this problem this is the mistak in this article

- new

in string to datetime code line no 5 datetime_object = datetime.strptime(datetime_str, ‘%m/%d/%y %H:%M:%S’) must be datetime_object = datetime.datetime.strptime(datetime_str, ‘%m/%d/%Y %H:%M:%S’) 1. datetime itself a module which have no strptime attribute. 2. %y must be %Y. A format is a format which cannot be changed.

- Keshav wadhwa

Very crisp and informative.Try more like this.

- Yogesh

Hello Sir, How can we convert Tue AUG 11 02:30:18 UTC 2020? I tried from datetime import datetime datetime_object =“” datetime_str = “Tue Aug 11 01:40:27 UTC 2020” try: datetime_object = datetime.strptime(datetime_str, ‘%A %B %d %H:%M:%S %Z %Y’) print(type(datetime_object)) print(datetime_object) except ValueError as ve: print(‘ValueError Raised:’, ve) But it is not working.Can you please help?

- Tiny Jimmy

Creative CommonsThis work is licensed under a Creative Commons Attribution-NonCommercial- ShareAlike 4.0 International License.
Join the Tech Talk
Success! Thank you! Please check your email for further details.

Please complete your information!

The developer cloud

Scale up as you grow — whether you're running one virtual machine or ten thousand.

Get started for free

Sign up and get $200 in credit for your first 60 days with DigitalOcean.*

*This promotional offer applies to new accounts only.