-2

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)
scharette
  • 9,437
  • 8
  • 33
  • 67
el_pup_le
  • 11,711
  • 26
  • 85
  • 142

3 Answers3

3

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.

scharette
  • 9,437
  • 8
  • 33
  • 67
1
import datetime
timestamp = datetime.datetime.strptime("2018-06-12", "%Y-%m-%d")
date_only = timestamp.date()
blue_note
  • 27,712
  • 9
  • 72
  • 90
0

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

Green Cloak Guy
  • 23,793
  • 4
  • 33
  • 53