-1

I have a string array of dates with this formula:

array(['2018-01-01 02:00:00 +01:00', '2018-01-01 04:00:00 +01:00',
    '2018-01-01 05:00:00 +01:00', ..., '2018-12-31 21:00:00 +01:00',
    '2018-12-31 22:00:00 +01:00', '2018-12-31 23:00:00 +01:00'],
   dtype='<U26')

I want to sort the dates by month and by hour, e.g:

2018-01-01 00:00:00 +01:00
2018-01-01 01:00:00 +01:00
2018-01-01 02:00:00 +01:00

and so on. I am using this mini code:

time1=time.sort()

but the sorting gives the month and all the values of an hour before moving to the next hour. Is there a way to sort these dates by hour according to each day of every month?

mkrieger1
  • 19,194
  • 5
  • 54
  • 65

1 Answers1

0
import datetime
dates = [datetime.datetime.strptime(ts, "%Y-%m-%d %H:%M:%S %z") for ts in timestamps]
dates.sort()
sorteddates = [datetime.datetime.strftime(ts, "%Y-%m-%d %H:%M:%S %z") for ts in dates]

Do double confirm if the DateTime format corresponds. https://www.w3schools.com/python/python_datetime.asp

Travis Tay
  • 350
  • 2
  • 10