Python计算指定日期是今年的第几天(三种方法)

小岛来信
小岛来信
发布时间:2026-10-13 | 5人浏览过
原创

本文介绍在Python中计算指定日期为当年第几天的三种方法。通过手动解析字符串、使用time库以及调用datetime库,分别实现日期天数统计。文章包含完整代码示例,并详细讲解闰年判断逻辑与月份天数累加过程,帮助读者掌握不同场景下的日期处理技巧。

面试背景与题目回顾

今日早些时候,我与腾讯面试官进行了一场视频面试。受限于麦克风音量、网络状况以及个人电脑性能较差等因素,我对面试结果并不乐观,感觉可能没有通过。

面试接近尾声时,面试官布置了一道基础计算题:计算给定日期是今年的第几天。

由于电脑运行卡顿,打字速度受到严重影响,我只能勉强写出部分代码。尽管面试官理解我的设备状况并知晓我的思路,最终并未要求我完成全部代码编写。

对此我深感惭愧,因此决定事后补全相关代码。接下来直接进入主题。

日期字符串解析方法

关于输入处理,我认为分别输入年、月、日较为初级,因此实现了两种解析形如“2020-3-26”字符串的方法,具体代码如下:


def cal_date_str_spilt(date):
 ''''
 处理形如"2020-3-26"
 使用字符串的spilt方法解析
 '''
 _year = int(date.split('-')[0])
 _month = int(date.split('-')[1])
 _day = int(date.split('-')[2])
 return [_year, _month, _day]

def cal_date_str_time(date):
 '''
 使用time库内置函数strptime(string, format) return struct_time对象
 传入参数:字符串 + 处理格式
 '''
 _date = time.strptime(date, '%Y-%m-%d')
 _year = _date.tm_year
 _month = _date.tm_mon
 _day = _date.tm_mday
 return [_year, _month, _day]

闰年判断逻辑

接下来需要判断是否为闰年。


def judge_leap_year(year, month):
 # 只有闰年且月份大于2月才加多一天
 if year % 400 == 0 or year % 100 and year % 4 == 0 and month > 2:
  return 1
 else:
  return 0

主函数实现与结果输出

主函数逻辑如下。


def main():
 date = input("请输入日期,以'-'分隔:")
 sum_1, sum_2 = 0, 0
 date_list_1 = cal_date_str_spilt(date)
 date_list_2 = cal_date_str_time(date)

 month_day = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
 month_day_lep = [31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]

 sum_1 += sum(month_day[:date_list_1[1] - 1]) + date_list_1[2] + judge_leap_year(date_list_1[0], date_list_1[1])
 sum_2 += sum(month_day[:date_list_2[1] - 1]) + date_list_2[2] + judge_leap_year(date_list_2[0], date_list_2[1])
 print('今天是今年的第' + str(sum_1) + '天')
 print('今天是今年的第' + str(sum_2) + '天')
 
 '''
 这一段是使用了datetime库的方法,python本身就有处理该类问题的方法
 '''
 _sum = datetime.date(date_list_1[0], date_list_1[1], date_list_1[2])
 sum_3 = _sum.strftime('%j')
 if sum_3[0] == '0' and sum_3[1] == '0':
  print('今天是今年的第' + str(sum_3[-1:]) + '天')
 elif sum_3[0] == '0':
  print('今天是今年的第' + str(sum_3[-2:]) + '天')
 else:
  print('今天是今年的第' + str(sum_3) + '天')

if __name__ == '__main__':
 main()

以下是完整代码示例:


import datetime
import time

def cal_date_str_spilt(date):
 ''''
 处理形如"2020-3-26"
 使用字符串的spilt方法解析
 '''
 _year = int(date.split('-')[0])
 _month = int(date.split('-')[1])
 _day = int(date.split('-')[2])
 return [_year, _month, _day]

def cal_date_str_time(date):
 '''
 使用time库内置函数strptime(string, format) return struct_time对象
 传入参数:字符串 + 处理格式
 '''
 _date = time.strptime(date, '%Y-%m-%d')
 _year = _date.tm_year
 _month = _date.tm_mon
 _day = _date.tm_mday
 return [_year, _month, _day]

def judge_leap_year(year, month):
 # 只有闰年且月份大于2月才加多一天
 if year % 400 == 0 or year % 100 and year % 4 == 0 and month > 2:
  return 1
 else:
  return 0

def main():
 date = input("请输入日期,以'-'分隔:")
 sum_1, sum_2 = 0, 0
 date_list_1 = cal_date_str_spilt(date)
 date_list_2 = cal_date_str_time(date)

 month_day = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
 month_day_lep = [31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]

 sum_1 += sum(month_day[:date_list_1[1] - 1]) + date_list_1[2] + judge_leap_year(date_list_1[0], date_list_1[1])
 sum_2 += sum(month_day[:date_list_2[1] - 1]) + date_list_2[2] + judge_leap_year(date_list_2[0], date_list_2[1])
 print('今天是今年的第' + str(sum_1) + '天')
 print('今天是今年的第' + str(sum_2) + '天')

 '''
 这一段是使用了datetime库的方法,python本身就有处理该类问题的方法
 '''
 _sum = datetime.date(date_list_1[0], date_list_1[1], date_list_1[2])
 sum_3 = _sum.strftime('%j')
 if sum_3[0] == '0' and sum_3[1] == '0':
  print('今天是今年的第' + str(sum_3[-1:]) + '天')
 elif sum_3[0] == '0':
  print('今天是今年的第' + str(sum_3[-2:]) + '天')
 else:
  print('今天是今年的第' + str(sum_3) + '天')

if __name__ == '__main__':
 main()

总结与扩展阅读

总结。

至此,关于Python三种方法计算指定日期是今年第几天的介绍结束。如需了解更多相关内容,可搜索本站过往文章或继续浏览下方推荐文章。感谢大家的支持!

相关标签:

本站声明

本文内容仅供参考,不代表本站观点。转载或引用请注明出处。如发现内容问题,请通过联系我们页面反馈。

Python 相关产品和应用

全部下载

专题列表