Python Dates

Python provides a built-in module called datetime for working with dates and times. This module allows you to create datetime objects, manipulate them, and format them according to your needs.

Getting the Current Date and Time

To get the current date and time, you can use the datetime module.

Tutorials dojo strip
  • datetime.now(): Returns the current local date and time.
Python

Creating Date Objects

You can create a date object by using the date class from the datetime module.

  • date(year, month, day): Creates a date object representing the specified date.
Python

Creating Time Objects

To create a time object, use the time class from the datetime module.

  • time(hour, minute, second): Creates a time object representing the specified time.
Python

Formatting Dates and Times

You can format date and time objects using the strftime method, which converts them into a string representation based on a specified format.

  • strftime(format): Returns a string representation of the date and time object, formatted according to the specified format.
Python

Parsing Dates and Times

You can parse a string representation of a date and time into a datetime object using the strptime method.

  • strptime(date_string, format): Parses a string representation of a date and time into a datetime object based on the specified format.
Python

Performing Date Arithmetic

You can perform arithmetic operations on datetime objects using the timedelta class.

  • timedelta(days, seconds, minutes): Represents a duration for performing date arithmetic.
Python

Python Dates Example Code

  • Get current date and time: Uses datetime.now() to get the current date and time.
  • Create date and time objects: Uses date and time classes to create specific date and time objects.
  • Format date and time: Uses strftime to format date and time into a string.
  • Parse date and time: Uses strptime to parse a string into a datetime object.
  • Date arithmetic: Uses timedelta to perform arithmetic operations on dates.
Python

Python Labs

Tutorials dojo strip