Python Program - Convert String to Datetime
here's a Python program that converts a string to a datetime object using the datetime module:
from datetime import datetime
# Define a string containing a date and time in ISO format
date_string = "2022-02-28T12:00:00Z"
# Parse the string into a datetime object using the datetime.fromisoformat() method
datetime_obj = datetime.fromisoformat(date_string)
# Print the datetime object
print("Datetime object:", datetime_obj)
In this program, we first import the datetime module, which provides classes for working with dates and times.
We then define a string called date_string containing a date and time in ISO format ("2022-02-28T12:00:00Z"). Note that the Z at the end of the string represents the UTC time zone.
To convert the string to a datetime object, we can use the datetime.fromisoformat() method, which takes a string in ISO format as its argument and returns a datetime object.
We assign the result of datetime.fromisoformat(date_string) to a variable called datetime_obj.
Finally, we can print the datetime object using the print() function. The output will be:
Datetime object: 2022-02-28 12:00:00+00:00
Note that the datetime.fromisoformat() method only works with strings in ISO format. If you need to parse a string in a different format, you can use the datetime.strptime() method and specify the format string. For example:
date_string = "28-Feb-2022 12:00:00 UTC" datetime_obj = datetime.strptime(date_string, "%d-%b-%Y %H:%M:%S %Z")
This code would parse the string "28-Feb-2022 12:00:00 UTC" using the format string "%d-%b-%Y %H:%M:%S %Z", which specifies the day, month, year, hour, minute, second, and time zone fields. Note that the %Z format code is used to parse the time zone name.
