askvity

How to Convert String to Datetime in Python?

Published in Python Datetime Conversion 4 mins read

In Python, you can convert a string to a datetime object using the datetime.strptime() method. This method parses a string representing a time according to a format, and returns a datetime object.

Understanding datetime.strptime()

The datetime.strptime() method is part of the datetime module and requires two main arguments:

  1. The string: The string that you want to convert into a datetime object.
  2. The format string: A string that specifies the format of the input string. This format string uses special directives (e.g., %Y, %m, %d) to indicate how the date and time components are represented in the string.

Example: Basic Conversion

from datetime import datetime

date_string = "2023-10-27 14:30:00"
format_string = "%Y-%m-%d %H:%M:%S"

datetime_object = datetime.strptime(date_string, format_string)

print(datetime_object)
print(type(datetime_object))

Output:

2023-10-27 14:30:00
<class 'datetime.datetime'>

In this example:

  • date_string holds the string representation of a date and time.
  • format_string specifies the format of date_string:
    • %Y: Four-digit year (e.g., 2023)
    • %m: Two-digit month (01-12)
    • %d: Two-digit day (01-31)
    • %H: Two-digit hour (00-23)
    • %M: Two-digit minute (00-59)
    • %S: Two-digit second (00-59)

Common Format Directives

Here's a table of commonly used format directives:

Directive Meaning Example
%Y Year with century (e.g., 2023) 2023
%y Year without century (00-99) 23
%m Month as a zero-padded decimal number (01-12) 01, 02,...
%B Month as locale's full name January
%b or %h Month as locale's abbreviated name Jan
%d Day of the month (01-31) 01, 02,...
%H Hour (24-hour clock) (00-23) 00, 01,...
%I Hour (12-hour clock) (01-12) 01, 02,...
%M Minute (00-59) 00, 01,...
%S Second (00-59) 00, 01,...
%f Microsecond (000000-999999) 000000,...
%p Locale's equivalent of AM/PM AM, PM
%a Locale's abbreviated weekday name Sun, Mon,...
%A Locale's full weekday name Sunday, Monday,...
%w Weekday as a decimal number, where 0 is Sunday and 6 is Saturday. 0, 1, 2,...
%j Day of the year as a zero-padded decimal number (001-366). 001, 002,...
%U Week number of the year (Sunday as the first day of the week). All days in a new year preceding the first Sunday are considered to be in week 0. (00-53) 00, 01,...
%W Week number of the year (Monday as the first day of the week). All days in a new year preceding the first Monday are considered to be in week 0. (00-53) 00, 01,...
%x Locale’s appropriate date representation. 10/27/23
%X Locale’s appropriate time representation. 14:30:00
%c Locale’s appropriate date and time representation. Fri Oct 27 14:30:00 2023
%Z Time zone name (empty string if the object is naive) EST, CDT
%z UTC offset in the form +HHMM or -HHMM (empty string if the the object is naive). +0000, -0400
%% A literal '%' character %

Handling Different String Formats

The key to successful conversion is matching the format_string to the actual format of your input string. Here are some examples:

from datetime import datetime

# Example 1: Date in the format "Month Day, Year"
date_string1 = "October 27, 2023"
format_string1 = "%B %d, %Y"
datetime_object1 = datetime.strptime(date_string1, format_string1)
print(datetime_object1)

# Example 2: Date and time in the format "Day/Month/Year Hour:Minute:Second"
date_string2 = "27/10/2023 14:30:00"
format_string2 = "%d/%m/%Y %H:%M:%S"
datetime_object2 = datetime.strptime(date_string2, format_string2)
print(datetime_object2)

# Example 3: Date in the format "Year-Month-Day"
date_string3 = "2023-10-27"
format_string3 = "%Y-%m-%d"
datetime_object3 = datetime.strptime(date_string3, format_string3)
print(datetime_object3)

Error Handling

If the format_string does not match the actual format of the date_string, strptime() will raise a ValueError. It's good practice to handle this exception:

from datetime import datetime

date_string = "2023-10-27"
format_string = "%Y/%m/%d" # Incorrect format

try:
    datetime_object = datetime.strptime(date_string, format_string)
    print(datetime_object)
except ValueError as e:
    print(f"Error: Invalid date format. {e}")

Conclusion

The datetime.strptime() method provides a flexible and powerful way to convert strings into datetime objects in Python. By understanding the various format directives and handling potential ValueError exceptions, you can accurately parse a wide range of date and time string formats.

Related Articles