有没有一个Python函数来确定一年中哪个季度的日期? [英] Is there a Python function to determine which quarter of the year a date is in?

查看:784
本文介绍了有没有一个Python函数来确定一年中哪个季度的日期?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

解决方案

我可以自己写这个,但是在我重新开始轮子之前,给定一个实例 x datetime.date (x.month-1)// 3 将给你这个季度(第一季度为0,第二季度为1 ,等等 - 如果需要从1代替,则添加1; - )。



编辑:原来是两个答案,多次upvoted甚至原来是ACCEPTED(目前都被删除),都是错误的 - 没有在分区之前执行 -1 ,而是除以4而不是3.由于。月份 1到12,很容易检查一下公式是否正确:

  for m in range(1,13):
print m // 4 + 1,
print

给出 1 1 1 2 2 2 2 3 3 3 3 4 - 两个四个月的季度和一个月的一个(eep)。

 $($ 1 $)$($)

$ b $ / code $

 

给出 1 1 1 2 2 2 3 3 3 4 4 4 - 现在不看非常喜欢你? - )



这证明这个问题是有道理的,我认为;-)。我不认为datetime模块应该有一切可能的有用的日历功能,但我知道我维护一个(经过良好测试的; -) datetools 模块使用我的(和其他人)的工作项目,有很多功能来执行所有这些日历计算 - 一些是复杂的,一些简单的,但没有任何理由一次又一次地做(甚至简单的工作)或风险错误在这样的计算中; - )。


Sure I could write this myself, but before I go reinventing the wheel is there a function that already does this?

解决方案

Given an instance x of datetime.date, (x.month-1)//3 will give you the quarter (0 for first quarter, 1 for second quarter, etc -- add 1 if you need to count from 1 instead;-).

Edit: originally two answers, multiply upvoted and even originally ACCEPTED (both currently deleted), were buggy -- not doing the -1 before the division, and dividing by 4 instead of 3. Since .month goes 1 to 12, it's easy to check for yourself what formula is right:

for m in range(1, 13):
  print m//4 + 1,
print

gives 1 1 1 2 2 2 2 3 3 3 3 4 -- two four-month quarters and a single-month one (eep).

for m in range(1, 13):
  print (m-1)//3 + 1,
print

gives 1 1 1 2 2 2 3 3 3 4 4 4 -- now doesn't this look vastly preferable to you?-)

This proves that the question is well warranted, I think;-). I don't think the datetime module should necessarily have every possible useful calendric function, but I do know I maintain a (well-tested;-) datetools module for the use of my (and others') projects at work, which has many little functions to perform all of these calendric computations -- some are complex, some simple, but there's no reason to do the work over and over (even simple work) or risk bugs in such computations;-).

这篇关于有没有一个Python函数来确定一年中哪个季度的日期?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆