How to Convert to Datetime in Python?

Estimated read time 2 min read

In Python, you can convert a string to a datetime object using the datetime module, which provides the strptime() function. The strptime() function allows you to parse a string according to a specified format and convert it to a datetime object.

Here’s an example of converting a string to a datetime object:

from datetime import datetime

date_string = "2023-05-28"
format_string = "%Y-%m-%d"

datetime_obj = datetime.strptime(date_string, format_string)

In this example, we import the datetime module and then define a string date_string representing a date in the format “YYYY-MM-DD”. We also define a format string format_string to match the format of the date string.

Next, we use the strptime() function and pass the date_string and format_string as arguments. This function parses the string according to the specified format and returns a datetime object, which we assign to the variable datetime_obj.

Finally, we print the datetime_obj, which will display the converted datetime object:

2023-05-28 00:00:00

Note that the strptime() function assumes the date string and format string match exactly. If the string format doesn’t match the specified format, a ValueError will be raised. Make sure the format string accurately reflects the format of the date string you want to convert.

You can then use the resulting datetime object for various operations, such as date arithmetic, formatting, or comparisons, depending on your requirements.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply