Write a Python Program to Convert String to Datetime

In Python, datetime is a module that allows you to work with dates, times, and timedeltas.

It provides a datetime class, which can be used to represent dates and times.

You can also use this module to convert a string to a datetime object.

In this tutorial, we will explore how to convert a string to datetime in Python.


To start, we need to import the datetime module.

We can do this by using the following code:

import datetime

Next, we need to create a string that we want to convert to datetime.

For example, we can use the following string:

date_string = '2022-08-23 14:45:00'

Once we have our date string, we can use the strptime() method of the datetime class to convert the string to a datetime object.

The strptime() method takes two arguments: the date string and a format string that specifies the format of the date string.

For example, the format string '%Y-%m-%d %H:%M:%S' specifies that the date string is in the format of ‘year-month-day hour:minute:second’.

Here’s how we can use the strptime() method to convert our date string:

datetime_object = datetime.datetime.strptime(date_string, '%%Y-%%m-%%d %%H:%%M:%%S')

In the above code, datetime_object is the datetime object that we get after converting the date string.

Now that we have converted our date string to a datetime object, we can use the datetime object to perform various operations.

For example, we can print the date and time using the strftime() method. The strftime() method takes a format string that specifies how the datetime object should be formatted.

For example, the format string '%Y-%m-%d %H:%M:%S' specifies that the datetime object should be formatted as ‘year-month-day hour:minute:second’.

Here’s how we can use the strftime() method to print the date and time:

pythonCopy codeprint(datetime_object.strftime('%Y-%m-%d %H:%M:%S'))

In the above code, we use the strftime() method to format the datetime object as ‘year-month-day hour:minute:second’ and then print it using the print() function.

That’s it!

You now know how to convert a string to datetime in Python using the datetime module.

Here’s the complete code:

import datetime

date_string = '2022-08-23 14:45:00'

datetime_object = datetime.datetime.strptime(date_string, '%%Y-%%m-%%d %%H:%%M:%%S')

print(datetime_object.strftime('%%Y-%%m-%%d %%H:%%M:%%S'))

In conclusion, converting a string to datetime in Python is a straightforward process.

We can use the strptime() method of the datetime class to convert a string to a datetime object.

The strptime() method takes a date string and a format string that specifies the format of the date string.

Once we have the datetime object, we can use various methods of the datetime class to perform operations on the date and time.

Finally, we can use the strftime() method to format the datetime object as a string.

By following these steps, we can easily convert a string to datetime in Python.