Dates

Preview: @ramanLamichhane8756805339 6 total contributions
ramanLamichhane8756805339's avatar
ramanLamichhane8756805339's avatar
@ramanLamichhane8756805339

6 total contributions

Published Oct 6, 2021Updated Jun 7, 2022
Contribute to Docs

Python has a built-in module called datetime that can be used to create and modify datetime objects.

Because the module comes built-in with Python, installation is not required, but we do need to import it at the top of a Python file.

Syntax

import datetime

Creating datetime Objects

The datetime module has three main types available:

  • date: Returns a date in the year-month-day format.
  • time: Returns a time in the hour-minute-second format with optional microsecond and timezone information.
  • datetime: Returns a date and time in the year-month-day and hour-minute-second formats.

Durations between any of these types can be returned by the .timedelta() method.

Dates

.datetime()
Returns a new object with date and time properties.
.strftime()
Format time and date objects into readable strings based on specified patterns.
.strptime()
Parses a string representing a date and time according to a specified format and returns a `datetime` object
.time()
Returns the seconds elapsed since the epoch.
datetime.date()
Returns a date object in the year-month-day format.
datetime.now()
Returns a datetime object representing the current local date and time.
datetime.timedelta()
Returns a timedelta object that represents the total difference between two dates, times, or datetime objects.

All contributors

  1. Preview: @ramanLamichhane8756805339 6 total contributions
    ramanLamichhane8756805339's avatar
    ramanLamichhane8756805339's avatar
    @ramanLamichhane8756805339

    6 total contributions

  2. Preview: @BrandonDusch 578 total contributions
    BrandonDusch's avatar
    BrandonDusch's avatar
    @BrandonDusch

    578 total contributions

  3. Preview: @lcart753 7 total contributions
    lcart753's avatar
    lcart753's avatar
    @lcart753

    7 total contributions

  4. Preview: Anonymous contributor 3126 total contributions
    Anonymous contributor's avatar
    Anonymous contributor

    3126 total contributions

  1. ramanLamichhane8756805339's avatar
    ramanLamichhane8756805339
  2. BrandonDusch's avatar
    BrandonDusch
  3. lcart753's avatar
    lcart753
  4. Anonymous contributor's avatar
    Anonymous contributor

Contribute to Docs

Learn Python on Codecademy

Morty Proxy This is a proxified and sanitized view of the page, visit original site.