python - 将月年对解析为日期时间

标签 python datetime

假设我有 2 个字符串“Jan-2010”和“Mar-2010”,我想解析它以返回 2 个日期时间对象:1-Jan-2010 和 31-Mar-2010(即最后一天).

Python 中最好的策略是什么?我是否应该将字符串拆分为标记或使用正则表达式,然后使用日历函数来获取“Mar-2010”月份的最后一天(获得第一天是微不足道的,在这种情况下它总是 1 除非我想要每个月的第一个工作日)。

有什么建议吗?提前致谢。

最佳答案

strptime 代表您将字符串解析为日期:

def firstofmonth(MmmYyyy):
  return datetime.datetime.strptime(MmmYyyy, '%b-%Y').date()

比乱用标记化、正则表达式和 &c!- 好得多。

要获取当月最后一天的日期,确实可以使用日历模块:

def lastofmonth(MmmYyyy):
  first = firstofmonth(MmmYyyy)
  _, lastday = calendar.monthrange(first.year, first.month)
  return datetime.date(first.year, first.month, lastday)

您几乎可以仅使用 datetime 来巧妙地完成它,例如,一种 ALMOST 工作方法:

def lastofmonth(MmmYyyy):
  first = firstofmonth(MmmYyyy)
  return first.replace(month=first.month+1, day=1
             ) - datetime.timedelta(days=1)

但是,唉!这在 12 月中断了,特殊化 12 月所需的代码使得整体方法比日历所能提供的更愚蠢;-)。

关于python - 将月年对解析为日期时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1273811/

相关文章:

python - 将数字转换为特殊的日期时间

python - 离线plot.ly无法在jupyter笔记本上工作

python - 为什么这不会附加到列表中?

php - 将日期转换为 unixtime php

javascript - 通过 Javascript 获取当前时间

datetime - 在将 json 反序列化为对象时,使用 jackson 将 asp.net/MS 专有 json Dateformat 转换为 java8 LocalDateTime

python - NumPy 相当于 MATLAB size()

python - Hadoop上的MrJob无法导入库

c# - 字符串到日期时间?扩展 Convert.* 或更好的东西

python - 随着时间的推移计算第二天有多少元素到达