开发者

python datetime help

开发者 https://www.devze.com 2023-01-11 18:08 出处:网络
I have a big search field, where users could type in any peice of text and it would search for it. Now I have a requirement to add in dob to my search. I am not adding a new textbox with a dob picke

I have a big search field, where users could type in any peice of text and it would search for it.

Now I have a requirement to add in dob to my search. I am not adding a new textbox with a dob picker. I just want users to be able to input a dob in a range of formats and it would figure it out.

IE users can search using any combination of these:

  • 25/08/1970
  • 25-08-1970
  • 1970/08/25
  • 1970-08-25

My program must figure out the dmy for each.

Is there a better way?

def parse(dob):
    for d in dob.split(" "):
       # find the dob
       if len(d) == 10:
           # its a dob
           if d[0:4].isdigit() # this is the year
               year = d[0:4]
               month = d[5:7]
               day = d[8:10]
            elif d[6:10].isdigit开发者_如何学JAVA() # this is the year
               day = d[0:2]
               month = d[3:5]
               year= d[6:10]


Python-dateutil should make your life much easier.

from dateutil.parser import parse as dparse
for each in ('25/08/1970', '25-08-1970', '1970/08/25', '1970-08-25'):
    dparse(each)

dparse(each) will return a datetime.datetime instance. You can pick up the date, month and year from the datetime instance.

Update

As mp0int pointed out, do remember to localize.


Dateutil.parser.parse is a nasty function and must be used carefully, such as

In [16]: parse('2010-05-01')
Out[16]: datetime.datetime(2010, 5, 1, 0, 0)

In [17]: parse('01-05-2010')
Out[17]: datetime.datetime(2010, 1, 5, 0, 0)

Localization is an important matter in date time format.

a = parse('01-05-2010')
a.astimezone(dateutil.tx.tzutc()) # not sure about dateutil.tx.tzutc()

probably this will resolve your problem, but i have not use it and i am not sure witch dateutil.tx function is what you need.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号