get the min date from a list

Ian Kelly ian.g.kelly at gmail.com
Thu Aug 14 13:24:59 EDT 2014


On Thu, Aug 14, 2014 at 8:10 AM, luofeiyu <elearn2014 at gmail.com> wrote:
> I finished it ,but how to make it into more pythonic way such as
>
> min (dates, key = converter)

The converter will be your changeToUnix function, but you'll need to
rework it to convert a single, rather than the whole list.

> def  changeToUnix(times):
>     import time,calendar,re
>     time_list=[]
>     for time1 in times:
>         pat='(.+?)([-|+]\d{4})(\(?.*\)?)'
>         x=re.search(pat,time1)
>         time_part=x.groups()[0].strip()
>         tz_part=x.groups()[1]
>         tz_acc=x.groups()[2].strip().replace('(','').replace(')','')
>         num=int(tz_part[1:3])
>         if tz_acc in ["","UTC","CST","GMT","EST","CST","PST"]:   num=num
>         if tz_acc in ["EDT"]:   num=num+2
>         if tz_acc in ["CDT"]:   num=num+1
>         if tz_acc in ["PDT"]:   num=num-1
>         op=tz_part[0]
>         y=time.strptime(time_part,"%a, %d %b %Y %H:%M:%S")
>         if op=="-":    hour=int(y.tm_hour)-num
>         if op=="+":    hour=int(y.tm_hour)+num
>         time2=(y.tm_year,y.tm_mon,y.tm_mday,hour,y.tm_min,y.tm_sec)
>         time_list.append(calendar.timegm(time2))
>     return(time_list)

This looks way overly complicated. Why are you trying to mess with the
time zone offset? strptime has a %z format code for parsing that
(although I would recommend using datetime.datetime.strptime since I'm
not sure how well time.strptime supports it). By adding the offset to
the hour like that, you could end up with an hour that falls outside
the accepted range. And I think you have your addition and subtraction
switched around anyway -- in effect you're doubling the time zone
offset, not converting to UTC. Also you would be losing the minutes
part of the time zone offset if you were to get something like +0545.
I also don't understand why you're special-casing and modifying three
of the time zones.

All you need to do is strip the parenthesized timezone off the string
if it's present, and pass the result to datetime.datetime.strptime.



More information about the Python-list mailing list