[英]How to get 1st calendar day of the current and next month based on a current date variable
I have a date variable calls today_date as below.我有一个日期变量调用 today_date,如下所示。 I need to get the 1st calendar day of the current and next month.
我需要得到当前和下个月的第一个日历日。 In my case, today_date is 4/17/2021, I need to create two more variables calls first_day_current which should be 4/1/2021, and first_day_next which should be 5/1/2021.
在我的例子中,today_date 是 2021 年 4 月 17 日,我需要创建另外两个变量调用 first_day_current 应该是 4/1/2021,first_day_next 应该是 5/1/2021。 Any suggestions are greatly appreciated
非常感谢任何建议
import datetime as dt
today_date
'2021-04-17'
Getting just the first date of a month is quite simple - since it equals 1
all the time.仅获取一个月的第一个日期非常简单——因为它始终等于
1
。 You can even do this without needing the datetime
module to simplify calculations for you, if today_date
is always a string "Year-Month-Day"
(or any consistent format - parse it accordingly)您甚至可以在不需要
datetime
模块的情况下为您简化计算,如果today_date
始终是字符串"Year-Month-Day"
(或任何一致的格式 - 相应地解析它)
today_date = '2021-04-17'
y, m, d = today_date.split('-')
first_day_current = f"{y}-{m}-01"
y, m = int(y), int(m)
first_day_next = f"{y+(m==12)}-{m%12+1}-01"
If you want to use datetime.date()
, then you'll anyway have to convert the string to (year, month, date) int
s to give as arguments (or do today_date = datetime.date.today()
. Then .replace(day=1)
to get first_day_current. datetime.timedelta
can't add months (only upto weeks), so you'll need to use other libraries for this . But it's more imports and calculations to do the same thing in effect.如果您想使用
datetime.date()
,那么无论如何您都必须将字符串转换为 (year, month, date) int
s 以给出 arguments (或执行today_date = datetime.date.today()
。然后.replace(day=1)
以获取 first_day_current. datetime.timedelta
不能添加月份(最多只能添加几周),因此您需要为此使用其他库。但是实际上要执行相同的操作需要更多的导入和计算。
I found out pd.offsets could accomplish this task as below -我发现 pd.offsets 可以完成以下任务 -
import datetime as dt
import pandas as pd
today_date #'2021-04-17' this is a variable that is being created in the program
first_day_current = today_date.replace(day=1) # this will be 2021-04-01
next_month = first_day_current + pd.offsets.MonthBegin(n=1)
first_day_next = next_month.strftime('%Y-%m-%d') # this will be 2021-05-01
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.