Day of Year Behaviour
Anna Martelli Ravenscroft
anna at aleax.it
Fri Oct 1 05:09:34 EDT 2004
Robert Brewer wrote:
> Hector Villafuerte wrote:
>
>>I have 2 fields:
>>YEAR
>>DAY_OF_YEAR
>>
>>and I need to get the complete date out of this, e.g.:
>>YEAR=2004
>>DAY_OF_YEAR=1
>>-> DATE=2004/Jan/1
>>
>>YEAR=2004
>>DAY_OF_YEAR=33
>>-> DATE=2004/Feb/2
>>
>>I'm using the time module without success:
>>
>>>>>time.localtime(time.mktime((2004, 0, 0, 0, 0, 0, 0, 1, 0)))
>>
>>(2003, 11, 30, 0, 0, 0, 6, 334, 0)
>
>
> One way to do it:
>
>
>>>>import datetime
>>>>YEAR = 2004
>>>>DAY_OF_YEAR = 33
>>>>d = datetime.date(YEAR, 1, 1) + datetime.timedelta(DAY_OF_YEAR - 1)
>>>>d
>
> datetime.date(2004, 2, 2)
Or a bit more explicit, using dateutil's yearday:
>>> import datetime
>>> from dateutil import relativedelta as rdel
>>> year = 2004
>>> d = datetime.date(year, 1, 1)
>>> date = d + rdel.relativedelta(yearday=33)
>>> print date
2004-02-02
There are a lot of handy things you can do with the dateutil package.
Anna
More information about the Python-list
mailing list