How to get the Current Year in Python
Table of Contents
Getting the current year is a common operation in any programming language.
In this post, we'll learn how to get the current year in Python.
Getting the current year
The recommended way to get the current year in Python is to use the datetime
module.
This module gives you built-in functions for working with dates and times.
We can use this module to import the date
class and then use the today
method to get today.
From there, we just need to use the year
method to get the year.
Let's see this in action:
PYTHONimport datetime
current_year = datetime.date.today().year
print(current_year)
BASH2022
The year is returned to us in a four-digit format as a string.
If you want it as a number, you'll have to convert it to an integer.
PYTHONimport datetime
current_year = int(datetime.date.today().year)
print(current_year)
BASH2022
Conclusion
In this post, we looked at the recommended way to get the current year in Python.
Simply import the datetime
module and use its built-in functionality to get the current year.
Hopefully, this has been helpful to you. Thanks for reading!
- Managing PHP Dependencies with Composer
- How to Serve Static Files with Nginx and Docker
- How to build a Discord bot using TypeScript
- How to deploy a PHP app using Docker
- How to deploy a MySQL Server using Docker
- How to deploy an Express app using Docker
- Using Puppeteer and Jest for End-to-End Testing
- Getting Started with Handlebars.js
- Getting User Location using JavaScript's Geolocation API
- Learn how to build a Slack Bot using Node.js
- Creating a Twitter bot with Node.js
- Building a Real-Time Note-Taking App with Vue and Firebase