1

This works !

>>> from datetime import date

>>> today=date(2011,10,11)

But how do I do this ?

>>> day =  '2011/10/11'

>>> today=date(day.split('/'))

note:

>>> day.split('/') 

['2011', '10', '11']

I have seen this link.But i need integers for the date() not a list

5 Answers 5

9

Use datetime.datetime.strptime(), which is designed specifically for parsing dates:

In [5]: datetime.datetime.strptime('2011/12/03', '%Y/%m/%d').date()
Out[5]: datetime.date(2011, 12, 3)
3

This should work:

date(*map(int, day.split('/')))

>>> map(int, day.split('/'))
[2011, 10, 11]
>>> date(*map(int, day.split('/')))
datetime.date(2011, 10, 11)
1
  • apologies for posting a dup, beat me by seconds, no reloads. +1
    – user237419
    Nov 10, 2011 at 14:16
2

Python has a special syntax for passing a sequence as the arguments:

today=date(*day.split('/'))

But the parameters also have to be ints, so you can use:

today=date(*map(int,day.split('/')))
1
  • passing a sequence as the arguments That was what i wanted to know.Thanks.But aix has the more appropriate answer.
    – Jibin
    Nov 11, 2011 at 9:47
2

You can loop over the list you get from day.split() and convert each entry to an int.

today = date([int(x) for x in day.split('/')]) 
0
>>> date( *(map(int,day.split('/'))))
datetime.date(2011, 10, 11)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.