Example HTML page

Date and Time

Date and Time modules

In Python, a datetime is one of the python modules. It provides the classes for manipulating date and time in simpler and complex ways.

To import the datetime module is shown in below;

>>> import datetime
>>> dir(datetime)
['MAXYEAR', 'MINYEAR', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', '_divide_and_round', 'date', 'datetime', 'datetime_CAPI', 'time', 'timedelta', 'timezone', 'tzinfo']

Date module

In python, the time module provides the functions that work with date and its conversions.

We can import date from datetime module as follows:

>>> from datetime import date
>>> dir(date)
['__add__', '__class__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__le__', '__lt__', '__ne__', '__new__', '__radd__', '__reduce__', '__reduce_ex__', '__repr__', '__rsub__', '__setattr__', '__sizeof__', '__str__', '__sub__', '__subclasshook__', 'ctime', 'day', 'fromordinal', 'fromtimestamp', 'isocalendar', 'isoformat', 'isoweekday', 'max', 'min', 'month', 'replace', 'resolution', 'strftime', 'timetuple', 'today', 'toordinal', 'weekday', 'year']

Functions of date module

The following are some of the functions of date module.

>>> date.__name__                                                      #Prints the name of module

‘date’

>>> date.__doc__

‘date(year, month, day) –> date object’

1. date.today( ) It displays today’s date.

Ex

>>> date.today( )

datetime.date(2018, 8, 3)

2. datetime.date.today( ) It displays current year, month and date.

Ex

>>> datetime.date.today()

datetime.date(2018, 8, 3)

3.datetime.date.min( ) It returns the earliest representable date.

Ex

>>> datetime.date.min

datetime.date(1, 1, 1)

4. datetime.date.max( ) It is similar to min(); max returns the latest representable date.

Ex

>>> datetime.date.max

datetime.date(9999, 12, 31)

5.datetime.date(year,month,day) The date function with three different attributes.

Ex

>>> d=datetime.date(2018,2,28)

>>> d.year

2018

>>> d.month

2

>>> d.day

28

6.replace( ) We can update any or all of those values by using replace().

Ex

>>> d=datetime.date(2018,2,28)

>>> d=d.replace(month=7,day=21)

>>> d

datetime.date(2018, 7, 21)

7 __str__( ) It displays the current local date as a string.

Ex

>>> d.__str__( )

‘2018-08-3’

8.ctime( ) It displays the current local date in a string format.

Ex

>>> d.ctime()

‘Sat Jul 21 00:00:00 2018’

Time module

In python, the time module provides the functions that work with time and its conversions.

To import time module as:

>>> import time
>>> dir(time)
['_STRUCT_TM_ITEMS', '__doc__', '__loader__', '__name__', '__package__', '__spec__', 'altzone', 'asctime', 'clock', 'ctime', 'daylight', 'get_clock_info', 'gmtime', 'localtime', 'mktime', 'monotonic', 'perf_counter', 'process_time', 'sleep', 'strftime', 'strptime', 'struct_time', 'time', 'timezone', 'tzname']

If you want the details of time module then give as follows;

>>> time.__name__	
'time'
>>> time.__doc__	#Give description about time module
'This module provides various functions to manipulate time values.\n\nThere are two standard representations of time.  One is the number\nof seconds since the Epoch, in UTC (a.k.a. GMT).  It may be an integer\nor a floating point number (to represent fractions of seconds).\nThe Epoch is system-defined; on Unix, it is generally January 1st, 1970.\nThe actual value can be retrieved by calling gmtime(0).\n\nThe other representation is a tuple of 9 integers giving local time.\nThe tuple items are:\n  year (including century, e.g. 1998)\n  month (1-12)\n  day (1-31)\n  hours (0-23)\n  minutes (0-59)\n  seconds (0-59)\n  weekday (0-6, Monday is 0)\n  Julian day (day in the year, 1-366)\n  DST (Daylight Savings Time) flag (-1, 0 or 1)\nIf the DST flag is 0, the time is given in the regular time zone;\nif it is 1, the time is given in the DST time zone;\nif it is -1, mktime() should guess based on the date and time.\n\nVariables:\n\ntimezone -- difference in seconds between UTC and local standard time\naltzone -- difference in  seconds between UTC and local DST time\ndaylight -- whether local time should reflect DST\ntzname -- tuple of (standard time zone name, DST time zone name)\n\nFunctions:\n\ntime() -- return current time in seconds since the Epoch as a float\nclock() -- return CPU time since process start as a float\nsleep() -- delay for a number of seconds given as a float\ngmtime() -- convert seconds since Epoch to UTC tuple\nlocaltime() -- convert seconds since Epoch to local time tuple\nasctime() -- convert time tuple to string\nctime() -- convert time in seconds to string\nmktime() -- convert local time tuple to seconds since Epoch\nstrftime() -- convert time tuple to string according to format specification\nstrptime() -- parse string to time tuple according to format specification\ntzset() -- change the local timezone'

Functions of time module

The following are some of the functions of time module.

1.time.asctime( ) This accepts a time-tuple and returns a readable 24-character string.

Ex

>>> time.asctime()

‘Fri Aug  3 16:56:05 2018’

 2. time.clock( )        This returns the current CPU time as a floating-point number of seconds. To measure computational costs of different approaches, the value of time.clock is more useful than that of time.time( ).

Ex:

>>> time.clock( )

1.7109298475989238e-06

3.time.ctime([secs]): It is similar to asctime(localtime(secs)) and without arguments is like asctime( ).

Ex:

>>> time.ctime( )

‘Fri Aug  3 17:03:15 2018’

4.time.gmtime([secs]): This accepts an instant expressed in seconds since the epoch and returns a time-tuple t with the UTC time.

Note : t.tm_isdst is always 0.

Ex

>>> time.time( )

1533296065.6616511

>>> time.gmtime(1533296065.6616511)

time.struct_time(tm_year=2018, tm_mon=8, tm_mday=3, tm_hour=11, tm_min=34, tm_sec=25, tm_wday=4, tm_yday=215, tm_isdst=0)

5 . time.sleep(secs)  Suspends the calling thread for secs seconds.

Ex:

>>> time.ctime()

‘Fri Aug  3 17:14:19 2018’

>>> print(“start:%s”%time.ctime())

start:Fri Aug  3 17:14:41 2018

>>> time.sleep(11)

>>> print(“end:%s”%time.ctime())

end:Fri Aug  3 17:15:21 2018

6.time.time( ) This returns the current time instant, a floating-point number of seconds since the epoch.

Ex

>>> time.time()

1533296785.6965158

 7.timetuple( ) It returns a tuple of attributes for the current local time.

Ex

>>> d.timetuple()

time.struct_time(tm_year=2018, tm_mon=7, tm_mday=21, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=5, tm_yday=202, tm_isdst=-1)

Example programs

1.Write a python program to know certain details of your bornday.

Program

import datetime
born = datetime.date(1993,12,13)                          #year, month, day
print(born.strftime("%Y"))        
print(born.strftime("%B"))                                            #Month of the year
print(born.strftime("%A"))                                            #Day of the week

Output

1993

December

Monday

2.Another example program on datetime module.

Program

import time
import datetime
print ("Time in seconds since the epoch: ", time.time( ))
print ("Current date and time: " , datetime.datetime.now( ))
print ("Or like this: " ,datetime.datetime.now( ).strftime("%y-%m-%d-%H-%M"))
print ("Current year: ", datetime.date.today( ).strftime("%Y"))
print ("Month of year: ", datetime.date.today( ).strftime("%B"))
print ("Week number of the year: ", datetime.date.today( ).strftime("%W"))
print ("Weekday of the week: ", datetime.date.today( ).strftime("%w"))
print ("Day of year: ", datetime.date.today( ).strftime("%j"))
print ("Day of the month : ", datetime.date.today( ).strftime("%d"))
print ("Day of week: ", datetime.date.today( ).strftime("%A"))

Output

Time in seconds since the epoch:  1533299183.585952

Current date and time:  2018-08-03 17:56:23.601552

Or like this:  18-08-03-17-56

Current year:  2018

Month of year:  August

Week number of the year:  31

Weekday of the week:  5

Day of year:  215

Day of the month :  03

Day of week:  Friday

3. A python program on Date operations.

Program

from datetime import date
now=date.today( )
print("Today's Date: " + now.strftime("%m/%d/%y"))
print("Today is : " + now.strftime("%A"))
print("Current Month is: " + now.strftime("%B"))

Output

Today’s Date: 08/03/18

Today is : Friday

Current Month is: August

Note : 

You can apply the following directives in the format, as per your need.

  • %a – abbreviated day of week
  • %A – full day of week
  • %b – abbreviated name of month
  • %B – full name of month
  • %c – preferred date and time representation
  • %C – century number (the year divided by 100; range 00 to 99)
  • %d – day of month (1 to 31)
  • %D – the same as %m/%d/%y
  • %e – day of month (1 to 31)
  • %g – like %G, but without the century
  • %G – 4-digit year corresponding to the ISO week number (ref. %V).
  • %h – same as %b
  • %H – hour; using a 24-hr clock (0 to 23)
  • %I – hour; using a 12-hr clock (1 to 12)
  • %j – day of year (1 to 366)
  • %m – month (1 to 12)
  • %M – minute
  • %n – newline character
  • %p – AM/PM according to given time value
  • %r – time in AM/PM representation
  • %R – time in 24-hr representation
  • %S – second
  • %t – tab
  • %T – current time; equal to %H:%M:%S
  • %u – day of week as a number (1 to 7); Monday=1
  • %U – week of year, beginning with the first Sunday as the first day of the first week
  • %V – The ISO 8601 week of year (1 to 53); week 1 is the first with at least 4 days in the current year, and with Monday as the first day of the week.
  • %W – week of year; beginning with the first Monday as the first day of the first week.
  • %w – day of week as a decimal; Sunday=0
  • %x – the preferred date representation without the time
  • %X – the preferred time representation without the date
  • %y – year without century (00 to 99)
  • %Y – year including century
  • %Z or %z – time zone/name/abbreviation
  • %% – a % character
Example HTML page

Leave a Reply

Your email address will not be published. Required fields are marked *

Pin It on Pinterest