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

Community
  • 1
  • 1
Jibin
  • 3,054
  • 7
  • 36
  • 51

5 Answers5

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)
NPE
  • 486,780
  • 108
  • 951
  • 1,012
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)
Dogbert
  • 212,659
  • 41
  • 396
  • 397
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('/')))
Vaughn Cato
  • 63,448
  • 5
  • 82
  • 132
  • **passing a sequence as the arguments** That was what i wanted to know.Thanks.But aix has the more appropriate answer. – Jibin Nov 11 '11 at 09: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('/')]) 
glglgl
  • 89,107
  • 13
  • 149
  • 217
ethan
  • 780
  • 7
  • 20
0
>>> date( *(map(int,day.split('/'))))
datetime.date(2011, 10, 11)
user237419
  • 8,829
  • 4
  • 31
  • 38