How to parse DST date in Python?

I have a date field in my dictionary Mon Apr 25 13:32:00 PDT 2013 I want to order my list of items by date.

dictionarylist.sort(key=operator(fieldposition) not working. Any help?

I also want to keep the time field?

Sample data (from comments):

 { '11163722404385': [ ('#3', 'Biology', 'A', 'Mon Apr 22 13:32:00 PDT 2013'), ('#3', '2089','Irdu', 'B', 'Wed Apr 10 15:31:00 PDT 2013') ], '1116372240485': [ ('#3', '2089','Biology', 'C', 'Mon Apr 25 13:32:00 PDT 2013'), ('#3', '2089', 'Math', 'A', 'Mon Apr 22 13:31:14 PDT 2013'), ('#3', '2089', 'Literature','C','Mon Apr 22 13:31:00 PDT 2013') ] } 
+4
source share
2 answers

First you have to convert date strings to python datetime objects, see datetime.strptime for converting a string to a datetime object.

Keep in mind that you will encounter problems in the time zone (unless you convert it to GMT offset). For work, it is recommended to use the dateutil module instead of datetime . The advantage is that dateutil easier to use and still returns datetime objects.

 from dateutil import parser dst_string = 'Mon Apr 25 13:32:00 PDT 2013' date_obj = parser.parse(dst_str) print date_obj >>> datetime.datetime(2013, 4, 25, 13, 32) 

Then you can sort the date of datetime objects.

 sorted(d['11163722404385'], key=lambda x: x[-1].date()) 

EDIT: Because @Mark Ransom pointed out that time zones can be especially complex. As a rule, you will have to handle abbreviations (PDT, EST, ...) yourself, as the time zone naming is not defined. You can learn more about handling reduced time zones with dateutil here .

+2
source

You can sort the list using key functions ( link ), which should convert date strings in time using strptime ( link ).

 import time def to_time(tup): return time.strptime(tup[4], "%a %b %d %X PDT %Y") sorted(defaultdict['1116372240485'], key=to_time) 

This will sort only your vocabulary words, not the entire dictionary.

+1
source

Source: https://habr.com/ru/post/1482243/


All Articles