python 年月日_在Python中将年/月/日转换为年

I'm using the Python "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 is sensitive of leap years. e.g. oday (March 6, 2009) is the 65th day of 2009. Here's web-based DateTime calculator.

Anyway, I see a two options:

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

Use datetime.timedelta to make a guess & then binary search for the correct day of 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 day of year. Any ideas/suggestions?

解决方案

There is a very simple solution:

day_of_year = datetime.now().timetuple().tm_yday

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值