1

I have the following working code:

import datetime

d = "2012-12-19"                
f = map(int,  d.split('-') )
day = datetime.date( f[0], f[1], f[2] )

print day

but when I try to write it this way:

day = datetime.date( f )

I get an exception: TypeError: an integer is required

Why is that and how could I write this better?

3 Answers 3

5

Best is to use the datetime.strptime() method:

datetime.datetime.strptime(d, '%Y-%m-%d').date()

Demo:

>>> import datetime
>>> d = "2012-12-19"                
>>> datetime.datetime.strptime(d, '%Y-%m-%d').date()
datetime.date(2012, 12, 19)

You are not passing f[0], etc. in though, your method would have worked had you done that or:

datetime.date(*f)
Sign up to request clarification or add additional context in comments.

Comments

1

Pack the argument list instead of passing it to date() as is:

day = datetime.date(*f)

Comments

1

Well, at least this is more readable:

day = datetime.date(year=f[0], month=f[1], day=f[2])

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.