Icon
Login    Register          




Most Advanced AI

Generate Code at the speed of Thought

Improve Productivity of Developers



Python Tutorial

Python Dates and Times

Python dates and times are a way to represent and manipulate date and time values in Python. They are represented by the datetime module, which provides a number of classes to work with dates and times.

The most basic class is the datetime.date class, which represents a single date. It has attributes for the year, month, and day. For example, to create a date object for the 4th of July, 2020:

date_obj = datetime.date(2020, 7, 4)

The datetime.time class represents a single time. It has attributes for the hour, minute, second, and microsecond. For example, to create a time object for 8:30 AM:

time_obj = datetime.time(8, 30)

The datetime.datetime class combines both date and time objects. It has attributes for the year, month, day, hour, minute, second, and microsecond. For example, to create a datetime object for 8:30 AM on the 4th of July, 2020:

datetime_obj = datetime.datetime(2020, 7, 4, 8, 30)

The datetime module also provides a number of functions for manipulating dates and times. For example, to add one day to a date object:

new_date = date_obj + datetime.timedelta(days=1)

To subtract one hour from a time object:

new_time = time_obj - datetime.timedelta(hours=1)

To convert a datetime object to a string:

date_string = datetime_obj.strftime('%Y-%m-%d %H:%M:%S')

Python dates and times are also useful for working with timezones. The datetime module provides the pytz module for working with timezones. For example, to create a datetime object for 8:30 AM in the Eastern timezone:

eastern_datetime = pytz.timezone('US/Eastern').localize(datetime_obj)

Finally, the datetime module provides a number of functions for formatting and parsing dates and times. For example, to format a date object as a string:

date_string = date_obj.strftime('%Y-%m-%d')

To parse a string into a date object:

date_obj = datetime.datetime.strptime('2020-07-04', '%Y-%m-%d')

Python dates and times are a powerful and convenient way to work with date and time values in Python.


Search Menu



Disclaimer:
Patodia Infotech Private Limited (fastdevai.com) has no responsibility for any text or code generated or for any action taken by you based on the contents provided by this web site. The use of this web site is solely at the user's risk. All the services are provided with the understanding that Patodia Infotech Private Limited or any other person or company associated with this company or website are not responsible for any loss or damage occurring to anybody from any code or contents generated by this website. Please note that text, codes and contents are generated by AI. These are state-of-the-art AI solutions. However, these are AI tools so there is no guarantee of accuracy of any code or contents generated.


Copyright © 2021-2024 Patodia Infotech Private Limited, All Rights Reserved.