Retrieve Current Date and Time in Python: A Practical Guide
Retrieve Current Date and Time in Python: A Practical Guide
Master how to fetch the current date and time in Python, and learn how to format them with strftime() for any project.
Video: Dates and Times in Python
Understanding dates and times is essential for logging, scheduling, and data analysis. Below we demonstrate reliable methods using Python’s built‑in datetime module.
Example 1: Getting Today’s Date
from datetime import date
today = date.today()
print("Today's date:", today)
We import the date class from datetime and call date.today() to retrieve the local date as a date object. This object can then be formatted into any string representation.
Example 2: Formatting the Current Date in Multiple Styles
from datetime import date
today = date.today()
# dd/mm/YYYY
print("d1 =", today.strftime("%d/%m/%Y"))
# Textual month, day and year
print("d2 =", today.strftime("%B %d, %Y"))
# mm/dd/YY
print("d3 =", today.strftime("%m/%d/%y"))
# Month abbreviation, day and year
print("d4 =", today.strftime("%b-%d-%Y"))
Typical output might look like:
d1 = 16/09/2019 d2 = September 16, 2019 d3 = 09/16/19 d4 = Sep-16-2019
If you need both date and time, use the datetime class.
Example 3: Getting the Current Date and Time
from datetime import datetime
# datetime object containing current date and time
now = datetime.now()
print("now =", now)
# dd/mm/YYYY HH:MM:SS
print("date and time =", now.strftime("%d/%m/%Y %H:%M:%S"))
Typical console output:
now = 2021-06-25 07:58:56.550604 date and time = 25/06/2021 07:58:56
Using datetime.now() gives you a complete timestamp, which you can then format to your preferred style with strftime().
Python
- Calculating Voltage and Current in Reactive DC Circuits
- Getting Started with Python: Install, Run, and Write Your First Program
- Mastering Python datetime: Practical Guide to Dates, Times, and Timezones
- Python: Retrieve Current Time and Timezone Data with Ease
- Mastering Python's time.sleep(): Best Practices, Multithreading, and Real‑World Examples
- How to Read and Write CSV Files in Python: A Comprehensive Guide
- Mastering Java Date and Time: Constructors, Methods & Best Practices
- Comprehensive Guide to Date and Time in C++
- Mastering Dates & Times in Python: A Practical Guide
- Arduino Weather Clock – Real-Time Date, Time, Temperature & Humidity Display