Working with Datetime in Python: A Beginner’s Guide

Dhruv Singhal
2 min readMay 6, 2023

--

If you’re working with dates and times in Python, you’ll need to use the datetime module. In this article, we’ll walk you through some common use cases for working with datetime, such as getting the current date and time, formatting dates, and more.

Getting the Current Date and Time: To get the current date and time in Python, you can use the datetime.now() method. Here are some examples:

from datetime import datetime

# Get the current date and time
now = datetime.now()
print(now)

This will output the current date and time in the following format: 2023-05-08 15:30:00.000000

Formatting Dates: You can format dates using the strftime() method. Here are some common format codes:

current_month = datetime.now().strftime('%m') # 02 (0-padded)
current_month_text = datetime.now().strftime('%h') # Feb
current_month_text = datetime.now().strftime('%B') # February

current_day = datetime.now().strftime('%d') # 23 (0-padded)
current_day_text = datetime.now().strftime('%a') # Fri
current_day_full_text = datetime.now().strftime('%A') # Friday

current_weekday_day_of_today = datetime.now().strftime('%w') # 5 (where 0 is Sunday and 6 is Saturday)

current_year_full = datetime.now().strftime('%Y') # 2018
current_year_short = datetime.now().strftime('%y') # 18 (without century)

current_second= datetime.now().strftime('%S') # 53
current_minute = datetime.now().strftime('%M') # 38
current_hour = datetime.now().strftime('%H') # 16 (24-hour format)
current_hour = datetime.now().strftime('%I') # 04 (12-hour format)

current_hour_am_pm = datetime.now().strftime('%p') # AM or PM

current_microseconds = datetime.now().strftime('%f') # 623596 (rarely needed)

current_timezone = datetime.now().strftime('%Z') # UTC, EST, CST, etc. (empty string if the object is naive)

In this article, we’ve covered some basic use cases for working with datetime in Python. By using the datetime module and its methods, you can easily work with dates and times in your Python code. Remember to always format your dates using the strftime() method to ensure they're in the correct format for your use case.

Any suggestions and comments would be greatly appreciated. If you found this article helpful, please like and share it with others. Don’t forget to follow me to stay up-to-date on my latest articles. Thank you for taking the time to read this!

--

--

Dhruv Singhal
Dhruv Singhal

Written by Dhruv Singhal

Data engineer with expertise in PySpark, SQL, Flask. Skilled in Databricks, Snowflake, and Datafactory. Published articles. Passionate about tech and games.

No responses yet