Fix Python – Datetime current year and month in Python

Question

Asked By – user3778327

I must have the current year and month in datetime.

I use this:

datem = datetime.today().strftime("%Y-%m")
datem = datetime.strptime(datem, "%Y-%m")

Is there maybe another way?

Now we will see solution for issue: Datetime current year and month in Python


Answer

Use:

from datetime import datetime
today = datetime.today()
datem = datetime(today.year, today.month, 1)

I assume you want the first of the month.

This question is answered By – llogiq

This answer is collected from stackoverflow and reviewed by FixPython community admins, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0