python 求日期
发布网友
发布时间:2022-04-23 15:08
我来回答
共4个回答
懂视网
时间:2022-04-18 13:19
第一种方法:
from datetime import datetime, timedelta
weekdays = ['Monday','Tuesday','Wednesday','Thursday',
'Friday','Saturday','Sunday']
def get_previous_byday(dayname, start_date=None):
if start_date is None:
start_date = datetime.today()
day_num = start_date.weekday()
day_num_target = weekdays.index(dayname)
days_ago = (7 + day_num - day_num_target) % 7
if days_ago == 0:
days_ago = 7
target_date = start_date - timedelta(days = days_ago)
return target_date
print( datetime.today() )
print( get_previous_byday('Monday') )
print( get_previous_byday('Monday', datetime(2016, 8, 28)) )
第二种方法,用dateutil模块
from datetime import datetime
from dateutil.relativedelta import relativedelta
from dateutil.rrule import *
d = datetime.now()
print(d)
print(d + relativedelta(weekday=FR))
print(d + relativedelta(weekday=FR(-1)))
热心网友
时间:2022-04-18 10:27
# -*- coding: cp936 -*-
#设置星期天的初始值为0
mondays=0
def getmonthdays(year):
isleapyear=year%400==0 or (year%4==0 and (not year%100==0))
if isleapyear:
return [31,29,31,30,31,30,31,31,30,31,30,31]
return [31,28,31,30,31,30,31,31,30,31,30,31]
#计算1899.12.31(这天是星期天)1901.1.1之间的天数
pastdays=1 #1899.12.31过一天是1900.1.1
monthdays=getmonthdays(1900)
for month in range (0,12):
pastdays+=monthdays[month]
#计算1901.1.1到2000.12.31星期天的数字
for year in range(1901,2001):
monthdays=getmonthdays(year)
for month in range(0,12):
if pastdays%7==0:
mondays+=1
pastdays+=monthdays[month]
print "1901年1月1月至2000年12月31日共有%d个星期天落在每月第一天"%mondays
追问%d不是c语言的吗
追答这些格式化字符串和C是差不多的,python语法是 “格式化字符串”%参数元组,和C的printf("格式化字符串"[,参数1,参数2,........,参数n])差不多
monday好像是星期一,sunday才是星期天,程序中的变量名起错了,反正这些变量名无关紧要。
a) 1900.1.1是星期一所以这天的前一天1899.12.31是星期天,然后每过七天就是星期天,程序计算1899.12.31到每月一号过去的天数,如果是七的倍数这天就是星期天
热心网友
时间:2022-04-18 11:45
暴力试出来?
能否用模块?
import datetime, time
ret=0
d0=datetime.date(1901,1,1)
while d0<=datetime.date(2000,12,31):
if time.strftime('%d',d0.timetuple())=='01' and time.strftime('%w',d0.timetuple())=='0':
ret+=1
d0+=datetime.timedelta(days=1)
print ret
热心网友
时间:2022-04-18 13:19
思路很简单:穷举出每个月的第一天,然后判断这一天是星期几:
# 示例程序,注意:程序未调试
# 返回days天后的星期号,星期天为0
def weekday_after_days(w, days):
return (w + days) % 7
# 返回下一月的年和月
def next_month_of_year(y, m):
m = m + 1 if m + 1 <= 12 else 1
y = y + 1 if m == 1 else y
return (y, m)
# 是否为润年
def is_leap_year(y):
return y % 4 == 0 and y % 100 != 0 or y % 400 == 0
# 计算一个月有几天
days_dict = [None, 31, 27, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
def days_in_month(y, m):
if m != 2:
return days_dict[m]
else:
return days_dict[m] if not is_leap_year(y) else days_dict[m] + 1
def main():
start = (1901, 1)
end = (2000, 12)
d = 1
while start[0] < end[0] or start[0] == end[0] and start[1] <= end[1]:
if d == 0:
yield start
else:
# 计算下月1日是星期几
d = (d + days_in_month(start[0], start[1])) % 7
# 计算下个月的年月
start = next_month_of_year(start[0], start[1])
追问27都出来了 拜托自己运行一下
追答我说过这个代码是没调试的。。。