I want to convert strings such as "2023-08-04T13:33:33.614Z" or "2023-05-06T05:55:00Z" to datetime object. Some strings have decimal digits in seconds (e.g. 2023-08-04T13:33:33 .614 Z) and some strings have not (e.g. 2023-05-06T05:55:00Z) raising error "time data %r does not match format"
How to solve it?
Full problem:
I'm trying to filter some data from dictionaries:
from datetime import datetime
def filter_by_time(dictionary_list, start_date, end_date):
filtered_list = []
for entry in dictionary_list:
time_str = entry['time']
entry_time = datetime.strptime(time_str, '%Y-%m-%dT%H:%M:%S.%fZ')
if start_date <= entry_time <= end_date:
filtered_list.append(entry)
return filtered_list
# Example list of dictionaries
data = [
{'name': 'Ana', 'city': 'New York', 'time': '2023-08-04T13:33:33.614Z'},
{'name': 'John', 'city': 'Los Angeles', 'time': '2023-05-12T16:53:20.349Z'},
{'name': 'Barney', 'city': 'Miami', 'time': '2023-05-09T16:49:20.752Z'},
{'name': 'Gabriel', 'city': 'Seattle', 'time': '2023-05-06T05:55:00Z'}
]
# Get user input for start_date and end_date
start_date_input = input("Enter the start date (YYYY-MM-DD): ")
end_date_input = input("Enter the end date (YYYY-MM-DD): ")
start_date = datetime.strptime(start_date_input, '%Y-%m-%d')
end_date = datetime.strptime(end_date_input, '%Y-%m-%d')
filtered_data = filter_by_time(data, start_date, end_date)
print("Filtered data:")
for entry in filtered_data:
print(entry)
When I try to filter values from 2023-05-01 to 2023-05-10, I got the following error:
raise ValueError("time data %r does not match format %r" %
ValueError: time data '2023-05-06T05:55:00Z' does not match format '%Y-%m-%dT%H:%M:%S.%fZ'
I noticed if I convert all my entries to three decimal digits in the seconds (e.g '2023-05-06T05:55:00Z' -> '2023-05-06T05:55:00.000Z', the error disappears.
How to filter my entries?