[Tutor] Finding numeric day in a year...

Steven D'Aprano steve at pearwood.info
Sat Jun 28 20:36:43 CEST 2014


On Sat, Jun 28, 2014 at 01:59:04PM -0400, Ken G. wrote:
> I know the correct answer should be 001, but I keep getting 179 which is 
> the correct answer for June 28, 2014 (I think). 

Day 179 of 2014 is June 28 according to my diary, which happens to be 
today. (Well, I'm in Australia, so for me it is yesterday, but for you 
it is today.) So when you do this:

print "Day of year: ", datetime.date.today().strftime("%j")

it prints the day of the year for *today*. If you try it again tomorrow, 
it will print 180. If you wait another week, it will print 187.

The existence of a variable "today" is irrelevant and has nothing to do 
with datetime.date.today. Consider this example:

py> import datetime
py> today = "the first day of the rest of your life"
py> datetime.date.today  # just inspect the method
<built-in method today of type object at 0x607ac0>
py> datetime.date.today()  # actually call the method
datetime.date(2014, 6, 29)
py> today
'the first day of the rest of your life'



> I tried using datecode 
> in various places instead of today but I am still getting 179.

datecode holds a string, not a date object. To call date methods, you 
need a date object.

py> the_day = datetime.date(2014, 1, 1)
py> the_day.strftime("%j")
'001'


If you have a date as a string, you can turn it into a date object like 
this:

py> the_day = datetime.datetime.strptime('20140101', '%Y%m%d')
py> the_day.strftime("%j")
'001'


-- 
Steven


More information about the Tutor mailing list