0

My code starts off by setting these 3 variables

var1 = 'Sep20'
var2 = '2020 09'
var3 = '2020-10-01'

How do I code such that var2 and var3 are functions of var1, so that I only have to set 1 variable? I would like to enter a string value for var1 and have var2 & var3 automatically calculated

Another example for a different month:

var1 = 'Dec20'      # a given month MMM YY
var2 = '2020 12'    # the same month YYYY MM
var3 = '2021-01-01' # the first day of the NEXT month YYYY-MM-DD
mina
  • 3
  • 3

2 Answers2

0

You can do this quite nicely with datetime

from datetime import date
from dateutil.relativedelta import relativedelta

d = date(2020, 12, 1)
var1 = d.strftime("%b%y")
var2 = d.strftime("%Y %m")
nextd = d + relativedelta(months=1)
var3 = nextd.strftime("%Y-%m-01")

See here for more info about relativedelta, and see here for more info about strftime.

ThisIsAQuestion
  • 1,887
  • 14
  • 20
  • i figured out `var1` & `var2` but did not know how to get to `var3`. thanks for the tip on `relativedelta`! – mina Dec 09 '20 at 20:43
0

The minimal example below relies on dateutil package:

from datetime import datetime
from dateutil import relativedelta

def date_func(year, month, day):
    x = datetime(year,month,day)
    first_next_month = x + relativedelta.relativedelta(months=1, day=1)
    
    return [
        x.strftime('%b%y'),
        x.strftime('%Y %m'),
        first_next_month.strftime('%Y-%m-%d')
    ]
zaxishere
  • 164
  • 1
  • 7