andrew.bober
andrew.bober

Reputation: 1

Python Date() Function

I have what may be a dopey question about Python's date function.

Let's say I want to pass the script a date, July 2nd 2013. This code works fine:

from datetime import date
july_2nd = date(2013,7,2)
print july_2nd

Output:

2013-07-02

So now what if I want to pass the date() function a value stored in a variable, which I can set with a function, rather than hard coding 7/2/13, so I try this and get an error:

from datetime import date
july_2nd = (2013,7,2)
print date(july_2nd)

Error message:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: an integer is required

Can anyone explain what's going on here?

Upvotes: 0

Views: 2294

Answers (1)

Martijn Pieters
Martijn Pieters

Reputation: 1122082

You want to pass in the tuple as separate arguments, using the *args splat syntax:

date(*july_2nd)

By prefixing july_2nd with an asterisk, you are telling Python to call date() with all values from that variable as separate parameters.

See the calls expression documentation for details; there is a **kwargs form as well to expand mapping into keyword arguments.

Upvotes: 2

Related Questions