The Program manipulation in Python involves the date and time. It’s not like checking up what time is it month python Program, it’s simply using the python program to manipulate date and time as an object through the built-in module called DateTime. This page is set to expose you to the fundamentals of how to work with Python Date.
At the end of this page, you’ll be good at Working with The Python Datetime Module. You’ll be learning the following:
- What is Python Date
- ItDate
- Time
- Datetime
- Tzinfo
- Timezones
- Date class Method
- Time class Method
- Datetime class method
- Operations in timedelta
Afterward, you’ll be all set for the python date-time operations
What is Python Datetime?
You already know the meaning of date and time in reality to be a parameter for measuring the duration of occurrences which ranges from microseconds, seconds, minutes, hours, months, years, and so on. However, Python date and time are not limited to measuring occurrences, they’re to be manipulated and worked with. The package that enables you to manipulate dates and times in Python is the DateTime module.
As mentioned earlier the Python Datetime is not actual data, it’s an object. Keep in mind that its manipulation is manipulating an object.
To further up, there are six main classes of the DateTime module, they are:
Date
The date object is a set of values that involves the year, the month, the day, and a collection of pythonic functions that are ideal to handle them.
Time
A time object is structured in a way that it has a set of values ranging from the hour, the minutes, the second, the microsecond, and the time zone information. choosing these values appropriately. Any time format can be represented by an accurate choice of the parameters.
Datetime
Is a combination of the set values of date and set values of the time. Which it’s a new set of Values. will range from microsecond, second, minute, hours, months, year, and timezone information.
TimeDelta
It represents the difference between two date times. Time Delta is a set of three values which are days, seconds, and microseconds. The Timedelta is priceless in its usefulness when it comes to the arithmetic operation on datetimes. Because it eliminates some necessary worries of how many seconds make one day and leap years.
tzinfo
This is simply an object that provides time zone information.
TimeZone
This is a class that uses the tzinfo abstract as a fixed offset.
Now that you’ve grasped some clearance on the datetime components, let’s delve in
Operation on Date
The date class is used to create date objects in Python. When the object of the date class is created, it takes the after the date in the format YYYY-MM-DD. The construction of this class needs three compulsory arguments such as year, month, and date.
The Constructor syntax: class DateTime.date(year, month, day)
The three arguments must be in the following range
- MINYEAR <= year <= MAXYEAR
- 1 <= month <= 12
- 1 <= day <= number of days in the given month and year
Remember that, If the argument is not an integer(whole number) it will raise a TypeError and if it is outside the range, it’ll raise ValueError.
Example:
Python Input
# Python program to # demonstrate date class # import the date class from datetime import date # initializing constructor # and passing arguments in the # format year, month, date my_date = date(1912, 10, 11) print("Date passed as argument is", my_date) # Uncommenting my_date = date(1996, 12, 39) # will raise an ValueError as it is # outside range # uncommenting my_date = date('1996', 12, 11) # will raise a TypeError as a string is # passed instead of integer
Output: Date passed as argument is 1912-10-11
Let’s get our current date
To get the current local date use the today() function of the date class. today() function comes with many attributes like a year, month, and day which can be printed individually.
Python Input
# Python program to # print current date from datetime import date # calling the today # function of date class today = date.today() print("Today's date is", today) Output Today's date is 2022-04-22
At the point of writing this, the current date was 2022-04-22
You can use the Timestamp
to get date objects from the timestamps method y=using the fromtimestamp() method. For the note, timestamp is the number of seconds from 1st January 1970 at UTC to a particular date.
Python Input
from datetime import datetime # Getting Datetime from timestamp date_time = datetime.fromtimestamp(1360239418) print("Datetime from timestamp:", date_time)
Output: Datetime from timestamp: 2013-02-07 13:16:58
Also you can convert date to string using two functions isoformat() and strftime().
Python Input
from datetime import date # calling the today # function of date class today = date.today() # Converting the date to the string Str = date.isoformat(today) print("String Representation", Str) print(type(Str))
Output: String Representation 2022-04-22 <class 'str'>
It’s important to know the list of the python Date class Method
List of Python Date Class Method
Function | Description |
astimezone() | Returns the DateTime object containing timezone information. |
combine() | Combines the date and time objects and returns a DateTime object |
ctime() | Returns a string representation of date and time |
date() | Return the Date class object |
fromisoformat() | Returns a datetime object from the string representation of the date and time |
fromordinal() | Returns a date object from the proleptic Gregorian ordinal, where January 1 of year 1 has ordinal 1. The hour, minute, second, and microsecond are 0 |
isocalendar() | Returns a tuple year, week, and weekday |
isoformat() | Return the string representation of the date and time |
isoweekday() | Returns the day of the week as an integer where Monday is 1 and Sunday is 7 |
now() | Returns current local date and time with tz parameter |
replace() | Changes the specific attributes of the DateTime object |
strftime() | Returns a string representation of the DateTime object with the given format |
strptime() | Returns a DateTime object corresponding to the date string |
time() | Return the Time class object |
timetuple() | Returns an object of type time.struct_time |
timetz() | Return the Time class object |
today() | Return local DateTime with tzinfo as None |
toordinal() | Return the proleptic Gregorian ordinal of the date, where January 1 of year 1 has ordinal 1 |
tzname() | Returns the name of the timezone |
utcfromtimestamp() | Return UTC from POSIX timestamp |
utcoffset() | Returns the UTC offset |
utcnow() | Return current UTC date and time |
weekday() | Returns the day of the week as an integer where Monday is 0 and Sunday is 6 |
Timedelta class
As you already know that Python timedelta class is used for calculating differences in dates. Interestingly it is one of the easiest ways to manipulate date in Python.
The constructor syntax: class datetime.timedelta(days=0, seconds=0, microseconds=0, milliseconds=0, minutes=0, hours=0, weeks=0)
Returns : Date
Example
Python Input
# Timedelta function demonstration from datetime import datetime, timedelta # Using current time ini_time_for_now = datetime.now() # printing initial_date print("initial_date", str(ini_time_for_now)) # Calculating future dates # for two years future_date_after_2yrs = ini_time_for_now + timedelta(days=730) future_date_after_2days = ini_time_for_now + timedelta(days=2) # printing calculated future_dates print('future_date_after_2yrs:', str(future_date_after_2yrs)) print('future_date_after_2days:', str(future_date_after_2days))
Output: initial_date 2022-04-22 13:11:16.489000 future_date_after_2yrs: 2024-04-21 13:11:16.489000 future_date_after_2days: 2022-04-24 13:11:16.489000
Let use the Timedelta to find the difference between two dates
Python Input
# Timedelta function demonstration from datetime import datetime, timedelta # Using current time ini_time_for_now = datetime.now() # printing initial_date print("initial_date", str(ini_time_for_now)) # Some another datetime new_final_time = ini_time_for_now + \ timedelta(days=2) # printing new final_date print("new_final_time", str(new_final_time)) # printing calculated past_dates print('Time difference:', str(new_final_time - ini_time_for_now))
Output: initial_date 2022-04-22 13:20:53.804000 new_final_time 2022-04-24 13:20:53.804000 Time difference: 2 days, 0:00:00
TimeDeltaIt Operators
The table below contains all the Operations supported by Python Timedelta
Function | Description |
Addition (+) | Adds and returns two timedelta objects |
Subtraction (-) | Subtracts and returns two timedelta objects |
Multiplication (*) | Multiplies timedelta object with float or int |
Division (/) | Divides the timedelta object with float or int |
Floor division (//) | Divides the timedelta object with float or int and return the int of floor value of the output |
Modulo (%) | Divides two timedelta object and returns the remainder |
+(timedelta) | Returns the same timedelta object |
-(timedelta) | Returns the resultant of -1*timedelta |
abs(timedelta) | Returns the +(timedelta) if timedelta.days > 1=0 else returns -(timedelta) |
str(timedelta) | Returns a string in the form (+/-) day[s], HH:MM:SS.UUUUUU |
repr(timedelta) | Returns the string representation in the form of the constructor call |
Format Datetime
Formatting Datetime is a very necessary skill in the python DateTime because the date representation may vary from place to place. For example in some countries, it can be dd-mm-yyyy and in other countries, it can be yyyy-mm-dd. You can format the Python Datetime using strptime and strftime functions.
Formatting Datetime using strptime
strftime() method returns a string representation of the given datetime format.
Example:
Python Input
# Python program to demonstrate # strftime() function from datetime import datetime as dt # Getting current date and time now = dt.now() print("Without formatting", now) # Example 1 s = now.strftime("%A %m %-Y") print('\nExample 1:', s) # Example 2 s = now.strftime("%a %-m %y") print('\nExample 2:', s) # Example 3 s = now.strftime("%-I %p %S") print('\nExample 3:', s) # Example 4 s = now.strftime("%H:%M:%S") print('\nExample 4:', s)
Output: Without formatting 2022-04-22 13:46:35.064000 Example 1: Friday 04 %-Y Example 2: Fri %-m 22 Example 3: %-I PM 35 Example 4: 13:46:35
Python DateTime strptime
strptime() converts the given string to a datetime object.
Example
Python Input
# import datetime module from datetime from datetime import datetime # consider the time stamps from a list in string # format DD/MM/YY H:M:S.micros time_data = ["25/05/99 02:35:8.023", "26/05/99 12:45:0.003", "27/05/99 07:35:5.523", "28/05/99 05:15:55.523"] # format the string in the given format : day/month/year # hours/minutes/seconds-micro seconds format_data = "%d/%m/%y %H:%M:%S.%f" # Using strptime with datetime we will format string # into datetime for i in time_data: print(datetime.strptime(i, format_data))
Output: 0099-05-25 02:35:08.230000 0099-05-26 12:45:00.300000 0099-05-27 07:35:05.523000 0099-05-28 05:15:55.523000
Handling Python DateTime timezone
Timezones in DateTime can be used in the case where one might want to display time according to the timezone of a specific region. This can be done using the pytz module of Python. This module serves the date-time conversion functionalities and helps users serving international client bases.
Example
Python Input
from datetime import datetime # current date and time now = datetime.now() t = now.strftime("%H:%M:%S") print("time:", t) s1 = now.strftime("%m/%d/%Y, %H:%M:%S") # mm/dd/YY H:M:S format print("s1:", s1) s2 = now.strftime("%d/%m/%Y, %H:%M:%S") # dd/mm/YY H:M:S format print("s2:", s2)
Output: time: 14:19:05 s1: 04/22/2022, 14:19:05 s2: 22/04/2022, 14:19:05
Summary
Python date and time are not limited to measuring occurrences, they’re to be manipulated and worked with. The package that enables you to manipulate date and time in Python is the datetime module.
The package that enables you manipulate date and time in Python is the datetime module.
Formatting Datetime is a very necessary skill in the python datetime because the date representation may vary from place to place.
There are six main classes of the datetime module, they are:
- Date
- Time
- Datetime
- TimeDelta
- Tzinfo
- Time zone
At the end of this page you’ve learned the following:
- What is Python Date
- ItDate
- Time
- Datetime
- Tzinfo
- Timezones
- Date class Method
- Time class Method
- Datetime class method
- Operations in timedelta
You have what it takes to secure better space in the python world. However, it is required that you put the ones you’ve learned into practice. For a helping hand see the Python Tutorials. Good luck Coding!