Get Current Year and Month with Python Datetime

Python's datetime module allows you to easily retrieve the current year and month. Here's how:

├Źndice
  1. Retrieve Current Year
  2. Retrieve Current Month

Retrieve Current Year


import datetime
current_year = datetime.datetime.now().year
print("Current year:", current_year)

This code imports the datetime module and uses the now() method to retrieve the current date and time. The year attribute is then accessed to retrieve the current year. The print() function is used to display the current year.

Retrieve Current Month


import datetime
current_month = datetime.datetime.now().strftime("%B")
print("Current month:", current_month)

This code also imports the datetime module and uses the now() method to retrieve the current date and time. The strftime() method is then used to format the current date and time as a string. The "%B" argument specifies that the string should include the full name of the current month. The resulting string is then assigned to the current_month variable, which is displayed using the print() function.

By combining these two pieces of code, you can retrieve both the current year and month:


import datetime
current_year = datetime.datetime.now().year
current_month = datetime.datetime.now().strftime("%B")
print("Current year:", current_year)
print("Current month:", current_month)

Using these methods, you can easily retrieve the current year and month in your Python programs.

Click to rate this post!
[Total: 0 Average: 0]

Related posts

Leave a Reply

Your email address will not be published. Required fields are marked *

Go up

Below we inform you of the use we make of the data we collect while browsing our pages. You can change your preferences at any time by accessing the link to the Privacy Area that you will find at the bottom of our main page. More Information