1

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
3
  • Take a look at datetime.datetime.strptime and datetime.datetime.strftime Commented Dec 9, 2020 at 20:22
  • Specifically look at the documentation for strftime() and strptime() Format Codes. Commented Dec 9, 2020 at 20:28
  • thanks i got part way there using these Commented Dec 9, 2020 at 20:38

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

i figured out var1 & var2 but did not know how to get to var3. thanks for the tip on relativedelta!
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')
    ]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.