Site icon FSIBLOG

How to Convert a Fetched String to Datetime in Python

How to Convert a Fetched String to Datetime in Python

How to Convert a Fetched String to Datetime in Python

I’m excited to share my journey with converting a fetched string to a datetime object in Python something I encountered during a Selenium project. I had successfully extracted data from a table on a webpage and formatted a “last seen” date into the format 04-07-25 (using %m-%d-%y). My objective was to compare this “last seen” date with the current date. However, I ran into an error because although I converted my current date properly, the fetched date remained stubbornly a string or was converted to an unexpected time value. Let me walk you through my initial error, explain what went wrong, and then show you a corrected solution with some additional, flexible functionality.

What Went Wrong in My Initial Code

Initially, my code was intended to take the extracted text from each table element, format it into a date string, and then convert it into a datetime.time object for comparison. Here’s a simplified version of my original approach with an embedded error:

datetime import datetime

# Current time is converted correctly
current_time = datetime.now() # Current datetime
now = current_time.strftime("%m-%d-%y") # Format current datetime as string "04-07-25"
print(now) # e.g., "04-07-25"
ntime = datetime.strptime(now, "%m-%d-%y").time() # Convert back to time object
print(type(ntime)) # <class 'datetime.time'>

# Simulated loop through table data (error example)
for t in ["04-08-25"]: # In real usage, `t.text` would be fetched from Selenium elements
# Attempt to extract parts of the date string from t.text
last_seen_month = str(t[0:1]).zfill(2) # Mistakenly taking only a single character slice
last_seen_day = str(t[2:3]).zfill(2) # Also a single character slice
last_seen_year = t[4:6]

last_seen_date = last_seen_month + "/" + last_seen_day + "/" + last_seen_year
last_seen_date = last_seen_date.replace("/", "-")
print(f'This is the last seen date: {last_seen_date}')

# Convert extracted string to time object
l_seen = datetime.strptime(last_seen_date, "%m-%d-%y").time()
print(type(l_seen))
print(l_seen)

Explanation of the Errors

Step-by-Step Corrected Example

I corrected the code by ensuring that I slice the extracted string properly. If the fetched string from Selenium is exactly in the format "04-08-25", there is no need to split and join manually. I can directly convert the string using datetime.strptime(). Here’s my corrected code:

datetime import datetime

# Correct conversion for current time
current_time = datetime.now()
now = current_time.strftime("%m-%d-%y")
print("Current date (string):", now)
ntime = datetime.strptime(now, "%m-%d-%y").time()
print("Current time type:", type(ntime))

# Simulating fetched date strings from Selenium table elements
# In a real scenario, these would come from t.text for each element
fetched_dates = ["04-08-25", "03-15-25"]

for t in fetched_dates:
# Direct conversion of the fetched date string to a datetime object
try:
# Convert fetched date string to a datetime.time object
l_seen = datetime.strptime(t, "%m-%d-%y").time()
except ValueError as e:
print(f"Error parsing '{t}': {e}")
continue

print(f"This is the last seen date: {t}")
print("Parsed last seen type:", type(l_seen))
print("Parsed last seen time:", l_seen)

Explanation of the Corrected Code

Extended Functionality for Practice

To add a bit more practice functionality, I enhanced the code to:

  1. Compare Fetched Date with Today’s Date:
    Convert both the current time and the fetched time to complete datetime objects (instead of just time) so I can compare the dates.
  2. Flexible Input Format:
    Support a second potential format (e.g., %Y-%m-%d) in case the fetched data might come in a different style.

Here’s the extended code:

datetime import datetime

def convert_string_to_datetime(date_str, formats=["%m-%d-%y", "%Y-%m-%d"]):
"""
Attempt to convert a date string to a datetime object using a list of potential formats.
"""
for fmt in formats:
try:
return datetime.strptime(date_str, fmt)
except ValueError:
continue
raise ValueError(f"Date '{date_str}' does not match any of the expected formats: {formats}")

# Get current datetime (not just time) for accurate date comparison
current_datetime = datetime.now()
print("Current datetime:", current_datetime)

# Simulated fetched date strings from Selenium (could have more than one format)
fetched_dates = ["04-08-25", "2025-04-08"]

for t in fetched_dates:
try:
# Convert fetched date string using the extended function
l_seen_datetime = convert_string_to_datetime(t)
except ValueError as e:
print(f"Error: {e}")
continue

# Compare dates (ignoring time part) by converting both to date objects
fetched_date_only = l_seen_datetime.date()
current_date_only = current_datetime.date()

print(f"\nFetched date: {t} -> {fetched_date_only}")
print(f"Current date: {current_date_only}")

# Example comparison: Check if fetched date is the same as the current date
if fetched_date_only == current_date_only:
print("The fetched date is today.")
elif fetched_date_only < current_date_only:
print("The fetched date is in the past.")
else:
print("The fetched date is in the future.")

Explanation of the Extended Functionality

Final Thought

This project was a fantastic exercise in debugging and enhancing a real-world coding task using Selenium and Python. I learned the critical importance of proper string handling and leveraging built-in datetime functions to avoid unnecessary errors. The extended functionality not only makes the code more robust but also provides me with a versatile tool for handling different date formats in my projects.

Exit mobile version