How can I convert this to a Python Date so I can find the latest date in a list?
["2018-06-12","2018-06-13", ...] to date
Then:
max(date_objects)
min(date_objects)
How can I convert this to a Python Date so I can find the latest date in a list?
["2018-06-12","2018-06-13", ...] to date
Then:
max(date_objects)
min(date_objects)
Since you want to convert from a list, you'll need to use my linked duplicate with a list comprehension,
from datetime import datetime
list_of_string_dates = ["2018-06-12","2018-06-13","2018-06-14","2018-06-15"]
list_of_dates= [datetime.strptime(date,"%Y-%m-%d") for date in list_of_string_dates]
print(max(list_of_dates)) # oldest
print(min(list_of_dates)) # earliest
2018-06-15 00:00:00
2018-06-12 00:00:00
Basically, you're converting the string representation of your dates to a Python date using datetime.strptime
and then applying max
and min
which are implemented on this type of objects.
import datetime
timestamp = datetime.datetime.strptime("2018-06-12", "%Y-%m-%d")
date_only = timestamp.date()
You can use the datetime
module. In particular, since your date is in the standard POSIX format, you'll be able to use the function date.fromtimestamp(timestamp)
to return a datetime object from your string; otherwise, you can use the strptime
function to read in a more complicated string - that has a few intricacies that you can figure out by looking at the documentation