欢迎访问宙启技术站
智能推送

Python'sdatetimefunctions–acompleteguide

发布时间:2023-10-25 17:03:22

Python's datetime module provides a wide range of functions to work with dates and times. In this guide, we will cover some of the most commonly used functions in the datetime module.

1. Date and Time Objects:

   - datetime.date(year, month, day): Creates a date object with the specified year, month, and day.

   - datetime.time(hour, minute, second, microsecond): Creates a time object with the specified hour, minute, second, and microsecond.

   - datetime.datetime(year, month, day, hour, minute, second, microsecond): Creates a datetime object with the specified year, month, day, hour, minute, second, and microsecond.

   - datetime.timedelta(days, seconds, microseconds, milliseconds, minutes, hours, weeks): Represents a duration or difference between two dates or times.

2. Current Date and Time:

   - datetime.datetime.now(): Returns the current local date and time.

   - datetime.datetime.today(): Returns the current local date and time.

3. Date and Time Formatting:

   - datetime.datetime.strftime(format): Returns a string representation of the date and time based on the specified format.

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

4. Date and Time Manipulation:

   - datetime.datetime.replace(year, month, day, hour, minute, second, microsecond): Returns a datetime object with the specified attributes replaced.

   - datetime.datetime + timedelta: Adds a duration to a datetime object and returns a new datetime object.

   - datetime.datetime - timedelta: Subtracts a duration from a datetime object and returns a new datetime object.

5. Timezone Support:

   - datetime.datetime.astimezone(timezone): Converts a naive datetime object to a timezone-aware datetime object.

   - datetime.datetime.now(timezone): Returns the current date and time in the specified timezone.

   - datetime.timezone(offset, name): Represents a fixed offset from UTC.

   - pytz module: A third-party library that provides support for more advanced timezone handling.

These are just some of the most commonly used functions in the datetime module. Python's datetime module offers many more functions and capabilities for working with dates and times. It is a powerful and flexible module that can handle a wide range of date and time-related operations in Python.