Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.4k views
in Technique[技术] by (71.8m points)

datetime - Convert Year/Month/Day to Day of Year in Python

I'm using the datetime module, i.e.:

>>> import datetime
>>> today = datetime.datetime.now()
>>> print(today)
2009-03-06 13:24:58.857946

and I would like to compute the day of year that takes leap years into account. e.g. today (March 6, 2009) is the 65th day of 2009.

I see a two options:

  1. Create a number_of_days_in_month = [31, 28, ...] array, decide if it's a leap year and manually sum up the days.

  2. Use datetime.timedelta to make a guess & then binary search for the correct day of the year:

    >>> import datetime
    >>> YEAR = 2009
    >>> DAY_OF_YEAR = 62
    >>> d = datetime.date(YEAR, 1, 1) + datetime.timedelta(DAY_OF_YEAR - 1)
    

These both feel pretty clunky & I have a gut feeling that there's a more "Pythonic" way of calculating the day of the year. Any ideas/suggestions?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Use datetime.timetuple() to convert your datetime object to a time.struct_time object then get its tm_yday property:

from datetime import datetime
day_of_year = datetime.now().timetuple().tm_yday  # returns 1 for January 1st

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...