GeezerVisonThe World Wide Web, restored to 800 pixels of glory. | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| Home|About|Gaming cabinet|Archives|How it works|Starter sites | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
GeezerVison is showing www.tutorialspoint.com — Python - Date and Time
Selected Reading
Python - Date and TimeA Python program can handle date and time in several ways. Converting between date formats is a common chore for computers. Following modules in Python's standard library handle date and time related processing −
What are Tick IntervalsTime intervals are floating-point numbers in units of seconds. Particular instants in time are expressed in seconds since 12:00am, January 1, 1970(epoch). There is a popular time module available in Python, which provides functions for working with times, and for converting between representations. The function time.time() returns the current system time in ticks since 12:00am, January 1, 1970(epoch). Exampleimport time # This is required to include time module.
ticks = time.time()
print ("Number of ticks since 12:00am, January 1, 1970:", ticks)
This would produce a result something as follows − Number of ticks since 12:00am, January 1, 1970: 1681928297.5316436 Date arithmetic is easy to do with ticks. However, dates before the epoch cannot be represented in this form. Dates in the far future also cannot be represented this way - the cutoff point is sometime in 2038 for UNIX and Windows. What is TimeTuple?Many of the Python's time functions handle time as a tuple of 9 numbers, as shown below −
For example, >>>import time >>> print (time.localtime()) This would produce an output as follows − time.struct_time(tm_year=2023, tm_mon=4, tm_mday=19, tm_hour=23, tm_min=49, tm_sec=8, tm_wday=2, tm_yday=109, tm_isdst=0) The above tuple is equivalent to struct_time structure. This structure has the following attributes −
Getting the Current TimeTo translate a time instant from seconds since the epoch floating-point value into a time-tuple, pass the floating-point value to a function (e.g., localtime) that returns a time-tuple with all valid nine items. import time
localtime = time.localtime(time.time())
print ("Local current time :", localtime)
This would produce the following result, which could be formatted in any other presentable form − Local current time : time.struct_time(tm_year=2023, tm_mon=4, tm_mday=19, tm_hour=23, tm_min=42, tm_sec=41, tm_wday=2, tm_yday=109, tm_isdst=0) Getting the Formatted TimeYou can format any time as per your requirement, but a simple method to get time in a readable format is asctime() − import time
localtime = time.asctime( time.localtime(time.time()) )
print ("Local current time :", localtime)
This would produce the following output − Local current time : Wed Apr 19 23:45:27 2023 Getting the Calendar for a MonthThe calendar module gives a wide range of methods to play with yearly and monthly calendars. Here, we print a calendar for a given month (Jan 2008). import calendar
cal = calendar.month(2023, 4)
print ("Here is the calendar:")
print (cal)
This would produce the following output − Here is the calendar:
April 2023
Mo Tu We Th Fr Sa Su
1 2
3 4 5 6 7 8 9
10 11 12 13 14 15 16
17 18 19 20 21 22 23
24 25 26 27 28 29 30
The time ModuleThere is a popular time module available in Python, which provides functions for working with times and for converting between representations. Here is the list of all available methods.
Let us go through the functions briefly. There are two important attributes available with time module. They are −
The calendar ModuleThe calendar module supplies calendar-related functions, including functions to print a text calendar for a given month or year. By default, calendar takes Monday as the first day of the week and Sunday as the last one. To change this, call the calendar.setfirstweekday() function. Here is a list of functions available with the calendar module −
Python datetime ModulePython's datetime module is included in the standard library. It consists of classes that help manipulate data and time data and perform date time arithmetic. Objects of datetime classes are either aware or nave. If the object includes timezone information it is aware, and if not it is classified as nave. An object of date class is nave, whereas time and datetime objects are aware. Python date ObjectA date object represents a date with year, month, and day. The current Gregorian calendar is indefinitely extended in both directions. Syntaxdatetime.date(year, month, day) Arguments must be integers, in the following ranges −
If the value of any argument outside those ranges is given, ValueError is raised. Examplefrom datetime import date
date1 = date(2023, 4, 19)
print("Date:", date1)
date2 = date(2023, 4, 31)
It will produce the following output − Date: 2023-04-19 Traceback (most recent call last): File "C:\Python311\hello.py", line 8, in <module> date2 = date(2023, 4, 31) ValueError: day is out of range for month date class attributes
Examplefrom datetime import date
# Getting min date
mindate = date.min
print("Minimum Date:", mindate)
# Getting max date
maxdate = date.max
print("Maximum Date:", maxdate)
Date1 = date(2023, 4, 20)
print("Year:", Date1.year)
print("Month:", Date1.month)
print("Day:", Date1.day)
It will produce the following output − Minimum Date: 0001-01-01 Maximum Date: 9999-12-31 Year: 2023 Month: 4 Day: 20 Class Methods in Date Class
Examplefrom datetime import date
print (date.today())
d1=date.fromisoformat('2023-04-20')
print (d1)
d2=date.fromisoformat('20230420')
print (d2)
d3=date.fromisoformat('2023-W16-4')
print (d3)
It will produce the following output − 2023-04-20 2023-04-20 2023-04-20 2023-04-20 Instance Methods in Date Class
Examplefrom datetime import date
d = date.fromordinal(738630) # 738630th day after 1. 1. 0001
print (d)
print (d.timetuple())
# Methods related to formatting string output
print (d.isoformat())
print (d.strftime("%d/%m/%y"))
print (d.strftime("%A %d. %B %Y"))
print (d.ctime())
print ('The {1} is {0:%d}, the {2} is {0:%B}.'.format(d, "day", "month"))
# Methods for to extracting 'components' under different calendars
t = d.timetuple()
for i in t:
print(i)
ic = d.isocalendar()
for i in ic:
print(i)
# A date object is immutable; all operations produce a new object
print (d.replace(month=5))
It will produce the following output − 2023-04-20 time.struct_time(tm_year=2023, tm_mon=4, tm_mday=20, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=3, tm_yday=110, tm_isdst=-1) 2023-04-20 20/04/23 Thursday 20. April 2023 Thu Apr 20 00:00:00 2023 The day is 20, the month is April. 2023 4 20 0 0 0 3 110 -1 2023 16 4 2023-05-20 Python time ModuleAn object time class represents the local time of the day. It is independent of any particular day. It the object contains the tzinfo details, it is the aware object. If it is None then the time object is the naive object. Syntaxdatetime.time(hour=0, minute=0, second=0, microsecond=0, tzinfo=None) All arguments are optional. tzinfo may be None, or an instance of a tzinfo subclass. The remaining arguments must be integers in the following ranges −
If any of the arguments are outside those ranges is given, ValueError is raised. Examplefrom datetime import time
time1 = time(8, 14, 36)
print("Time:", time1)
time2 = time(minute = 12)
print("time", time2)
time3 = time()
print("time", time3)
time4 = time(hour = 26)
It will produce the following output − Time: 08:14:36 time 00:12:00 time 00:00:00 Traceback (most recent call last): File "/home/cg/root/64b912f27faef/main.py", line 12, in Class attributes
Examplefrom datetime import time print(time.min) print(time.max) print (time.resolution) It will produce the following output − 00:00:00 23:59:59.999999 0:00:00.000001 Instance attributes
Examplefrom datetime import time t = time(8,23,45,5000) print(t.hour) print(t.minute) print (t.second) print (t.microsecond) It will produce the following output − 8 23 455000 Instance Methods of time Object
Python datetime objectAn object of datetime class contains the information of date and time together. It assumes the current Gregorian calendar extended in both directions; like a time object, and there are exactly 3600*24 seconds in every day. Syntaxdatetime.datetime(year, month, day, hour=0, minute=0, second=0, microsecond=0, tzinfo=None, *, fold=0) The year, month and day arguments are required.
If any argument in outside ranges is given, ValueError is raised. Examplefrom datetime import datetime dt = datetime(2023, 4, 20) print(dt) dt = datetime(2023, 4, 20, 11, 6, 32, 5000) print(dt) It will produce the following output − 2023-04-20 00:00:00 2023-04-20 11:06:32.005000 Class attributes
Examplefrom datetime import datetime
min = datetime.min
print("Min DateTime ", min)
max = datetime.max
print("Max DateTime ", max)
It will produce the following output − Min DateTime 0001-01-01 00:00:00 Max DateTime 9999-12-31 23:59:59.999999 Instance Attributes of datetime Object
Examplefrom datetime import datetime
dt = datetime.now()
print("Day: ", dt.day)
print("Month: ", dt.month)
print("Year: ", dt.year)
print("Hour: ", dt.hour)
print("Minute: ", dt.minute)
print("Second: ", dt.second)
It will produce the following output − Day: 20 Month: 4 Year: 2023 Hour: 15 Minute: 5 Second: 52 Class Methods of datetime Object
Instance Methods of datetime Object
Examplefrom datetime import datetime, date, time, timezone
# Using datetime.combine()
d = date(2022, 4, 20)
t = time(12, 30)
datetime.combine(d, t)
# Using datetime.now()
d = datetime.now()
print (d)
# Using datetime.strptime()
dt = datetime.strptime("23/04/20 16:30", "%d/%m/%y %H:%M")
# Using datetime.timetuple() to get tuple of all attributes
tt = dt.timetuple()
for it in tt:
print(it)
# Date in ISO format
ic = dt.isocalendar()
for it in ic:
print(it)
It will produce the following output − 2023-04-20 15:12:49.816343 2020 4 23 16 30 0 3 114 -1 2020 17 4 Python timedelta ObjectThe timedelta object represents the duration between two dates or two time objects. Syntaxdatetime.timedelta(days=0, seconds=0, microseconds=0, milliseconds=0, minutes=0, hours=0, weeks=0) Internally, the attributes are stored in days, seconds and microseconds. Other arguments are converted to those units −
While days, seconds and microseconds are then normalized so that the representation is unique. ExampleThe following example shows that Python internally stores days, seconds and microseconds only. from datetime import timedelta delta = timedelta( days=100, seconds=27, microseconds=10, milliseconds=29000, minutes=5, hours=12, weeks=2 ) # Only days, seconds, and microseconds remain print (delta) It will produce the following output − 114 days, 12:05:56.000010 ExampleThe following example shows how to add timedelta object to a datetime object. from datetime import datetime, timedelta
date1 = datetime.now()
date2= date1+timedelta(days = 4)
print("Date after 4 days:", date2)
date3 = date1-timedelta(15)
print("Date before 15 days:", date3)
It will produce the following output − Date after 4 days: 2023-04-24 18:05:39.509905 Date before 15 days: 2023-04-05 18:05:39.509905 Class Attributes of timedelta Object
Examplefrom datetime import timedelta
# Getting minimum value
min = timedelta.min
print("Minimum value:", min)
max = timedelta.max
print("Maximum value", max)
It will produce the following output − Minimum value: -999999999 days, 0:00:00 Maximum value 999999999 days, 23:59:59.999999 Instance Attributes of timedelta ObjectSince only day, second and microseconds are stored internally, those are the only instance attributes for a timedelta object.
Instance Methods of timedelta Objecttimedelta.total_seconds() − Return the total number of seconds contained in the duration. Examplefrom datetime import timedelta year = timedelta(days=365) years = 5 * year print (years) print (years.days // 365) 646 year_1 = years // 5 print(year_1.days) It will produce the following output − 1825 days, 0:00:00 5 365 Advertisements
| ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| You are visitor 01402503 — GeezerVison does not store the pages you look up. Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required. |