In Python, you can parse a datetime string into a datetime object using the datetime.strptime() method. This method takes two arguments: the datetime string to be parsed, and a format string that specifies the format of the datetime string.
Here's an example code that parses a datetime string in ISO 8601 format:
from datetime import datetimedatetime_str = '2023-03-14T13:30:45.000Z'# Define the format stringformat_str = '%Y-%m-%dT%H:%M:%S.%fZ'# Parse the datetime string into a datetime objectdatetime_obj = datetime.strptime(datetime_str, format_str)print('Datetime object:', datetime_obj) |
In this code, we define a datetime string in ISO 8601 format and a format string that corresponds to that format. We then pass these two values to the datetime.strptime() method, which returns a datetime object representing the parsed datetime. Finally, we print the datetime object using the print() function.
Note that the format string uses special codes to represent the different parts of the datetime string. For example, %Y represents the year with four digits, %m represents the month with two digits, %d represents the day with two digits, %H represents the hour with two digits in 24-hour format, %M represents the minute with two digits, %S represents the second with two digits, and %f represents the fraction of the second with up to six digits. The Z character at the end of the format string represents the UTC time zone.