Table of Contents

Every serious developer, even at the beginning of their journey, eventually faces a common challenge — handling date and time. Whether you're building a blog, a data processing tool, or an event scheduler, working with time-related data is inevitable. Tasks like logging, time zone conversions, date validation, or calculating time differences come up regularly in real-world projects.

Python provides powerful, built-in tools for working with dates and times, but many beginners struggle with understanding its structure and syntax. That's why mastering this topic early will give you a strong foundation and help you avoid painful bugs later. This guide walks you through the basics of working with dates and times in the programming language — clearly, professionally, and with real examples.

If you don’t understand how time works in your application, your application doesn’t work.

How to Get the Current Date and Time in Python?

Getting the current date and time is one of the first and most essential things you should learn. Python includes the datetime module, which provides everything you need to work with both date and time objects. The most direct way to fetch the current moment is to use datetime.now(), which returns the current local date and time as a single object.

This object includes the year, month, day, hour, minute, second, and microsecond — all in one call. You can then format or extract parts of this object depending on what your program needs. This is especially useful in log generation, file naming, and timestamping events.

Here's how to get started:


    from datetime import datetime

    now = datetime.now()
    print(now)  # Output: 2025-06-02 15:27:43.562781
  

In this example, now holds the current date and time, including microseconds. The output format is YYYY-MM-DD HH:MM:SS.mmmmmm, which is the default representation of a datetime object.

You can also use datetime.today(), which returns the same result as now() without any timezone awareness. But for most use cases, now() is your go-to method.

How to Print Current Date and Time in Python?

Once you've retrieved the current date and time using datetime.now(), printing it is simple — just use the print() function. However, the output includes both the date and time in a raw format that may not be easy to read. To improve readability or customize the format, use the strftime() method. This function allows you to define how the output should look using format codes. It’s a must-know if you’re working on any user-facing application or generating logs.

  • %Y — Full year (e.g., 2025)
  • %m — Month as two digits (e.g., 06)
  • %d — Day of the month (e.g., 02)
  • %H — Hour in 24-hour format (e.g., 15)
  • %M — Minutes (e.g., 45)
  • %S — Seconds (e.g., 09)

    from datetime import datetime

    now = datetime.now()
    formatted = now.strftime("%Y-%m-%d %H:%M:%S")
    print(formatted)  # Output: 2025-06-02 15:45:09
  

In this example, the strftime() method formats the date and time into a more readable string. You can customize the format to suit your needs, whether for logging, user interfaces, or data storage.

How to Get Date in Python Without Time?

In many situations, you only need the date — without hours, minutes, or seconds. To achieve this, use the date() method from a datetime object. This strips away the time portion and returns only the date. It’s commonly used in reports, UI elements, and when comparing days without considering exact times. The output is a date object, which still allows formatting and comparison.


    from datetime import datetime

    today = datetime.now().date()
    print(today)  # Output: 2025-06-02
  

In this example, today holds the current date without any time information. The output is in the format YYYY-MM-DD, which is standard for date representation.

You can also extract individual parts like year, month, or day from the result if needed.

How to Remove Time from Date?

If you have a datetime object and want to remove the time portion, use the .date() method. This returns a date object containing only the year, month, and day. It’s a common step when comparing dates without needing time precision. It also simplifies data for reporting, summaries, and grouping operations. The resulting object still supports formatting and comparisons.


    from datetime import datetime

    dt = datetime.now()
    only_date = dt.date()
    print(only_date)  # Output: 2025-06-02
  

In this example, only_date holds the date part of the current datetime, effectively removing the time. This is useful when you want to focus solely on the date aspect in your application logic.

How to Convert Datetime to String?

To convert a datetime object into a string, use the strftime() method. It lets you define the output format using specific formatting codes like %Y for year or %d for day. This is often used for displaying timestamps in user interfaces, saving filenames, or exporting logs. Formatting makes date data more readable and standardized across your application. You can include separators, full month names, and more.


    from datetime import datetime

    now = datetime.now()
    formatted = now.strftime("%d/%m/%Y %H:%M:%S")
    print(formatted)  # Output: 02/06/2025 16:32:05
  

In this example, the datetime object is formatted into a string that includes the day, month, year, hour, minute, and second. This format is often used in logs or user-facing applications where clarity is essential.

How to Add Date and Time?

You can perform addition with date and time using the timedelta class from the datetime module. This allows you to shift a datetime forward by days, hours, minutes, or even weeks. Adding time is essential for scheduling events, setting expiration dates, or calculating reminders. Just create a timedelta with your desired interval and add it to a datetime object. The result is a new datetime with the added duration.


    from datetime import datetime, timedelta

    now = datetime.now()
    future = now + timedelta(days=3, hours=2)
    print(future)  # Output: 2025-06-05 18:32:05
  

In this example, we add 3 days and 2 hours to the current datetime. The timedelta class makes it easy to manipulate time values without complex calculations. This is particularly useful in applications like booking systems, reminders, and scheduling tasks.

What You Will Learn?

This section gives you a solid understanding of how to work with date and time in the programming language. You’ll explore the standard tools, learn how to interpret and format data, and manipulate time values accurately. Each topic is written with clarity and practical relevance, based on my years of real-world development and teaching. These fundamentals are not just theoretical — they’re the core of writing reliable, production-ready code.

Datetime Module

In this part, you’ll learn how to use the datetime module, the standard tool in Python for working with dates and times. The module contains essential classes like date, time, datetime, and timedelta. Each class serves a distinct purpose, and understanding their role is critical for writing maintainable code.

Learn More →

Parse and Format Date

This topic focuses on two critical tasks: converting strings to date/time objects (parsing) and converting date/time objects to strings (formatting). You’ll understand how real-world applications store or display dates in different formats, and how your code can adapt to that. You’ll dive into the strptime() method to parse dates from user input, log files, or APIs.

Learn More →

Timedelta Calculations

Time arithmetic is the backbone of scheduling, tracking durations, and analyzing events. This section introduces the timedelta class, which is used to represent the difference between two date/time values. You’ll learn how to subtract two datetime objects to find elapsed time, and how to add or subtract durations to shift dates forward or backward.

Learn More →

Comparing Dates

One of the most practical use cases in development is comparing and sorting dates. Whether you're filtering expired entries, determining which event happens first, or displaying dates in order — comparison logic matters. This section teaches how to use relational operators like <, >, == to compare datetime and date objects.

Learn More →

Frequently Asked Questions

How do I convert a string to a datetime object in Python?

To convert a string into a datetime object, you should use the strptime() method from the datetime module. This function allows you to specify the format of the input string, so Python knows exactly how to interpret the components like year, month, and day. For example, if your string is "2025-06-02", you would use datetime.strptime("2025-06-02", "%Y-%m-%d").

This is especially useful when dealing with user input, log files, or data from APIs where dates are returned as plain text. Make sure the format string matches the input exactly, otherwise you'll get a ValueError. Parsing strings into date objects is one of the most common tasks in data preprocessing, and doing it correctly ensures your time-related logic remains accurate and reliable.

What is the difference between naive and aware datetime objects?

A naive datetime object does not contain any timezone information. It simply represents a point in time without any context of where on the globe it belongs. On the other hand, an aware datetime object includes timezone information, usually handled through Python’s pytz or zoneinfo libraries. This makes it suitable for operations across time zones, like scheduling meetings for users in different countries.

You must never mix naive and aware objects in comparisons or arithmetic, as it will raise an exception. Always standardize your datetime inputs when working in production systems, especially in applications like logging, analytics, and notifications. Being aware of this distinction from the start will save you from major bugs that are difficult to trace in distributed environments.

How to convert date to epoch time in Python?

To convert a date or datetime object to epoch time (also called Unix timestamp), use the timestamp() method. This method returns the number of seconds since January 1, 1970 (UTC). It’s often used in APIs, databases, or logging systems that require numeric time values for storage or comparison. However, keep in mind that the timestamp() method only works with aware or properly localized datetime objects.

For example, datetime(2025, 6, 2).timestamp() will return a float representing seconds. You can round it or convert it to an integer if needed. Also note that timestamp() always returns time in UTC. If your datetime object is naive (without timezone), the result assumes local time and may lead to inconsistencies in distributed systems. Always check timezone awareness before converting to epoch time.

How do I handle date calculations across different time zones in Python?

Handling time zones correctly requires converting datetime objects to “aware” versions using libraries like zoneinfo (standard since Python 3.9) or pytz. These tools allow you to assign a specific time zone to your datetime values, ensuring that arithmetic and comparisons are accurate across regions. For example, converting a timestamp from UTC to US Eastern Time is possible by attaching the appropriate zone and using astimezone().

Never perform calculations with naive datetime objects across time zones — it will lead to incorrect results. Also, be careful with daylight saving transitions, which can break assumptions if not handled properly. Time zone logic is critical for scheduling apps, global systems, and applications that serve users in different locations. When in doubt, normalize all datetime inputs to UTC and convert to local time only for display.

What libraries are available in Python for date and time calculations?

The built-in datetime module is the default and most reliable tool for basic operations like getting current time, formatting, parsing, and arithmetic. For timezone handling, zoneinfo (Python 3.9+) is recommended as it’s part of the standard library. If you're using older Python versions, pytz is the most widely used third-party package for timezone-aware datetime objects.

For more advanced needs like natural language parsing or working with recurring events, consider libraries like dateutil, which extends datetime functionality. If you're working with time series data, pandas provides powerful datetime indexing and resampling capabilities. Each library fits different use cases, so understanding their strengths helps you choose the right tool for your project and maintain clean, readable code.