Python Program to Convert String to Datetime
datetime is a built-in module in Python that provides classes for working with dates and times. It allows you to create, manipulate, and format dates, times, and time intervals, as well as perform arithmetic and comparison operations on them.
Some of the classes provided by the datetime module include:
1. date: Represents a date (year, month, day) 2. time: Represents a time of day (hour, minute, second, microsecond) 3. datetime: Represents a specific date and time (combines the date and time classes) 4. timedelta: Represents a duration of time (difference between two dates or times)
The datetime module also provides various functions for working with dates and times, such as datetime.now() to get the current date and time, and datetime.strptime() to parse a date and time string into a datetime object.
Python Code :
The below Python program converts a string to a datetime object:
# Import necessary libraries from datetime import datetime # Example usage date_string = "2023-02-28 15:30:00" date_object = datetime.strptime(date_string, '%Y-%m-%d %H:%M:%S') print(date_object)
In this program, we first import the datetime class from the datetime module. We then define a string that represents a date and time in the format of “YYYY-MM-DD HH:MM:SS”.
We use the strptime method of the datetime class to convert the string to a datetime object. The strptime method takes two arguments: the string to be converted and a format string that specifies the format of the string.
In this case, we use the format string ‘%Y-%m-%d %H:%M:%S’, which tells the strptime method that the string is in the format of “YYYY-MM-DD HH:MM:SS”. The resulting datetime object is then printed to the console. Output:
Note that if the string is not in the correct format, the strptime method will raise a ValueError.