Python Tutorial

Python Flow Control

Python Functions

Python Data Types

Python Date and Time

Python Files

Python String

Python List

Python Dictionary

Python Variable

Python Input/Output

Python Exceptions

Python Advanced

strptime() to read and parse datetime string in Python

In this tutorial, we'll learn how to use strptime() from the datetime module to read and parse datetime strings in Python.

The strptime() function is part of the datetime class in the datetime module. It takes a datetime string and a format string as arguments and returns a datetime object.

Here's a step-by-step guide on how to use strptime():

  • Import the datetime module:
from datetime import datetime
  • Define the datetime string and the format string:
datetime_string = "2023-05-02 14:30:00"
format_string = "%Y-%m-%d %H:%M:%S"

The format string uses special format codes to represent the different components of the datetime string, such as %Y for the year, %m for the month, %d for the day, %H for the hour (24-hour format), %M for the minute, and %S for the second.

  • Use strptime() to parse the datetime string:
parsed_datetime = datetime.strptime(datetime_string, format_string)
  • Print the parsed datetime object:
print(parsed_datetime)

Here's the complete code:

from datetime import datetime

datetime_string = "2023-05-02 14:30:00"
format_string = "%Y-%m-%d %H:%M:%S"

parsed_datetime = datetime.strptime(datetime_string, format_string)

print(parsed_datetime)

Output:

2023-05-02 14:30:00

The strptime() function allows you to parse datetime strings with various formats.

  1. How to use strptime() to parse datetime in Python:

    • Description: Using the strptime() method from the datetime module to parse a string into a datetime object.
    • Code:
      from datetime import datetime
      
      date_string = "2023-12-25"
      parsed_date = datetime.strptime(date_string, "%Y-%m-%d")
      print(parsed_date)
      
  2. Parsing datetime strings with strptime() in Python:

    • Description: Parsing datetime strings into datetime objects using strptime().
    • Code:
      from datetime import datetime
      
      datetime_string = "2023-12-25 12:30:00"
      parsed_datetime = datetime.strptime(datetime_string, "%Y-%m-%d %H:%M:%S")
      print(parsed_datetime)
      
  3. Datetime string to datetime object with strptime() in Python:

    • Description: Converting a datetime string to a datetime object using strptime().
    • Code:
      from datetime import datetime
      
      datetime_str = "2023-12-25 18:45:30"
      dt_object = datetime.strptime(datetime_str, "%Y-%m-%d %H:%M:%S")
      print(dt_object)
      
  4. Using strptime() with strftime() for datetime conversion in Python:

    • Description: Using strptime() to parse a string and then strftime() to format it back to a string.
    • Code:
      from datetime import datetime
      
      original_string = "2023-12-25 12:30:00"
      parsed_datetime = datetime.strptime(original_string, "%Y-%m-%d %H:%M:%S")
      formatted_string = parsed_datetime.strftime("%A, %B %d, %Y %I:%M%p")
      print(formatted_string)
      
  5. Parsing date and time from a string with strptime() in Python:

    • Description: Parsing date and time components from a string using strptime().
    • Code:
      from datetime import datetime
      
      date_time_str = "2023-12-25 18:45:30"
      dt_object = datetime.strptime(date_time_str, "%Y-%m-%d %H:%M:%S")
      print(f"Date: {dt_object.date()}, Time: {dt_object.time()}")
      
  6. Convert string to datetime using strptime() and format in Python:

    • Description: Converting a string to a datetime object using strptime() and specifying the format.
    • Code:
      from datetime import datetime
      
      date_string = "25-12-2023"
      parsed_date = datetime.strptime(date_string, "%d-%m-%Y")
      print(parsed_date)
      
  7. Handling different datetime formats with strptime() in Python:

    • Description: Handling parsing of datetime strings with different formats using strptime().
    • Code:
      from datetime import datetime
      
      date_str1 = "2023-12-25"
      date_str2 = "12/25/2023"
      
      parsed_date1 = datetime.strptime(date_str1, "%Y-%m-%d")
      parsed_date2 = datetime.strptime(date_str2, "%m/%d/%Y")
      
      print(parsed_date1, parsed_date2)
      
  8. Parsing datetime strings with different time zones in Python:

    • Description: Parsing datetime strings with time zones using strptime() and pytz.
    • Code:
      from datetime import datetime
      import pytz
      
      datetime_str = "2023-12-25 12:30:00 UTC"
      dt_object = datetime.strptime(datetime_str, "%Y-%m-%d %H:%M:%S %Z")
      dt_object_utc = dt_object.replace(tzinfo=pytz.utc)
      
      print(dt_object_utc)
      
  9. Using strptime() with %z for timezone in Python:

    • Description: Parsing datetime strings with timezone information using %z in strptime().
    • Code:
      from datetime import datetime
      
      datetime_str = "2023-12-25 12:30:00 +0500"
      dt_object = datetime.strptime(datetime_str, "%Y-%m-%d %H:%M:%S %z")
      print(dt_object)
      
  10. Converting custom date formats with strptime() in Python:

    • Description: Converting custom date formats using strptime() for parsing.
    • Code:
      from datetime import datetime
      
      date_str = "25th Dec, 2023"
      dt_object = datetime.strptime(date_str, "%dth %b, %Y")
      print(dt_object)
      
  11. Parsing dates with strptime() and dateutil.parser in Python:

    • Description: Using dateutil.parser for flexible datetime parsing with strptime().
    • Code:
      from dateutil import parser
      
      date_str = "December 25, 2023 12:30 PM"
      dt_object = parser.parse(date_str)
      print(dt_object)
      
  12. Handling microseconds with strptime() in Python:

    • Description: Parsing datetime strings with microseconds using strptime().
    • Code:
      from datetime import datetime
      
      datetime_str = "2023-12-25 12:30:00.500000"
      dt_object = datetime.strptime(datetime_str, "%Y-%m-%d %H:%M:%S.%f")
      print(dt_object)
      
  13. Parsing datetime strings with strptime() and timedelta in Python:

    • Description: Parsing datetime strings and adjusting with timedelta using strptime().
    • Code:
      from datetime import datetime, timedelta
      
      datetime_str = "2023-12-25 12:30:00"
      dt_object = datetime.strptime(datetime_str, "%Y-%m-%d %H:%M:%S")
      adjusted_datetime = dt_object + timedelta(hours=2)
      
      print(adjusted_datetime)
      
  14. Error handling for invalid datetime strings with strptime() in Python:

    • Description: Adding error handling for parsing invalid datetime strings with strptime().
    • Code:
      from datetime import datetime
      
      datetime_str = "Invalid Date"
      try:
          dt_object = datetime.strptime(datetime_str, "%Y-%m-%d")
          print(dt_object)
      except ValueError as e:
          print(f"Error: {e}")