Dates
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.
- .datetime.now()
- Returns the current date and timestamp.
- .strftime()
- Format time and date objects into readable strings based on specified patterns.
- .strptime()
- Returns a datetime object that represents the parsed date and time from the given string, based on the specified format.
- .time()
- Returns the seconds elapsed since the epoch.
- datetime.date()
- Returns a date object in the year-month-day format.
- datetime.timedelta()
- Returns a duration, resolved to microseconds, that occurs between dates, times, and datetimes.
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.
Learn Python on Codecademy
- Career path
Computer Science
Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!Includes 6 CoursesWith Professional CertificationBeginner Friendly75 hours - Course
Learn Python 3
Learn the basics of Python 3.12, one of the most powerful, versatile, and in-demand programming languages today.With CertificateBeginner Friendly23 hours