Python Tutorial | Python Date and Time Inbuilt Function

Python Inbuilt Functions
What are Python Inbuilt Functions?
* String Inbuilt Functions
* Math Inbuilt Functions
* Date and Time Inbuilt Function
* Random Inbuilt Functions

String Inbuilt Functions     Math Inbuilt Functions   Date and Time Inbuilt Function   Random Inbuilt Functions

Python datetime

Python has a module named datetime to work with dates and times. Let’s see few simple programs related to date and time.

Example:1

To display date and time

#to display date and time
import datetime
dt = datetime.datetime.now()
print(dt)

Output:

2020-04-04 11:05:41.299535
>>>

In the above example, we have imported datetime module using import datetime statement.

One of the classes defined in the datetime module is datetime class. We then used now() method to create a datetime object containing the current local date and time.

Example 2: Get Current Date

To display only date

#to display only date
import datetime
dt = datetime.date.today()
print(dt)

Output:

2020-04-04
>>>

In this program, we have used today() method defined in the date class to get a date object containing the current local date.

Example:3

Get current date
we can create a date object containing the current date by using a class method named today().

from datetime import date
today = date.today()
print("Current date =", today)

Output:

Current date = 2020-04-04
>>>

Example:4

To display day , month and year parts
Print today’s year, month and day
We can get year, month, day, day of the week etc. from the date object easily.

from datetime import date
# date object of today's date
today = date.today() 

print("Current year:", today.year)
print("Current month:", today.month)
print("Current day:", today.day)

Output:

Current year: 2020
Current month: 4
Current day: 4
>>>

Example:5

To display hour, min and sec parts

from datetime import datetime
#from user define date
#a = datetime(2017, 11, 28, 23, 55, 59, 342380)
#from system date and time
#datetime_object = datetime.datetime.now()

a = datetime.now()
#to display day,month and year
print("year =", a.year)
print("month =", a.month)
print("day =", a.day)
#to display hour,min and sec
print("hour =", a.hour)
print("minute =", a.minute)
print("timestamp =", a.timestamp())

Output:

year = 2020
month = 4
day = 4
hour = 11
minute = 12
timestamp = 1585978963.361214
>>>

Example:6

Example : Get date from a timestamp
We can also create date objects from a timestamp. A Unix timestamp is the number of seconds between a particular date and January 1, 1970. You can convert a timestamp to date using fromtimestamp() method.

from datetime import datetime
from datetime import date 

a = datetime.now()
#to display day,month and year
print("year =", a.year)
print("month =", a.month)
print("day =", a.day)
#to display hour,min and sec
print("hour =", a.hour)
print("minute =", a.minute)
print("timestamp =", a.timestamp())

Output:

year = 2020
month = 4
day = 4
hour = 11
minute = 14
timestamp = 1585979049.569976
>>>

Python format datetime

The way date and time is represented may be different in different places, organizations etc. It’s more common to use mm/dd/yyyy in the US, whereas dd/mm/yyyy is more common in the UK.
Python has strftime() and strptime() methods to handle this.

Example:7

Python strftime() – datetime object to string
The strftime() method is defined under classes date, datetime and time. The method creates a formatted string from a given date, datetime or time object.

Example : Format date using strftime()

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: 11:16:29
s1: 04/04/2020, 11:16:29
s2: 04/04/2020, 11:16:29
>>>

Here, %Y, %m, %d, %H etc. are format codes. The strftime() method takes one or more format codes and returns a formatted string based on it.
In the above program, t, s1 and s2 are strings.
• %Y – year [0001,…, 2018, 2019,…, 9999]
• %m – month [01, 02, …, 11, 12]
• %d – day [01, 02, …, 30, 31]
• %H – hour [00, 01, …, 22, 23
• %M – month [00, 01, …, 58, 59]
• %S – second [00, 01, …, 58, 59]

Python strptime() – string to datetime

The strptime() method creates a datetime object from a given string (representing date and time).

Example:8

#for pre defined date
from datetime import datetime
date_string = "23 July, 2019"
print("date_string =", date_string)

date_object = datetime.strptime(date_string, "%d %B, %Y")
print("date_object =", date_object)

#from timestamp (from current date

from datetime import date 
a=datetime.now()
ts=a.timestamp()
d1=date.fromtimestamp(ts)
print(ts)
print(d1)
print(d1.day," ",d1.month," ",d1.year)

Output:

date_string = 23 July, 2019
date_object = 2019-07-23 00:00:00
1585979667.318726
2020-04-04
4 4 2020
>>>

Example:9

from datetime import datetime
date_string = "23 July, 2019"
print("date_string =", date_string)
date_object = datetime.strptime(date_string, "%d %B, %Y")
print("date_object =", date_object)

Output:

date_string = 23 July, 2019
date_object = 2019-07-23 00:00:00
>>>

By the way, %d, %B and %Y format codes are used for day, month(full name) and year respectively.

Example:10

Today’s Weekday Number

The date.today() function also gives you the weekday number. Here is the Weekday Table which start with Monday as 0 and Sunday as 6

Day WeekDay Number
Monday 0
Tuesday 1
Wednesday 2
Thursday 3
Friday 4
Saturday 5
Sunday 6

Weekday Number is useful for arrays whose index is dependent on the Day of the week.

#to display date and time
import datetime
dt= datetime.datetime.now()
print(dt)
dt=datetime.date
print(dt.today())
today=dt.today()
#month
y=today.year
m=today.month
d=today.day
#yy/mm/dd
print("date is "+str(y)+"/"+str(m)+"/"+str(d))
print("date is ",y,"/",m,"/",d)

#dd/mm/yy
print("date is "+str(d)+"/"+str(m)+"/"+str(y))
print("date is ",d,"/",m,"/",y)

#to display week days
w=today.weekday()
print(w)

days=["mon","tue","wed","thru","fri","sat","sun"]
print("week days : ",days[w])

Output:

2020-04-04 11:28:58.142955
2020-04-04
date is 2020/4/4
date is 2020 / 4 / 4
date is 4/4/2020
date is 4 / 4 / 2020
5
week days : sat
>>>

Example:11

from datetime import date
from datetime import time
from datetime import datetime
def main():
    ##DATETIME OBJECTS
    #Get today's date from datetime class
    today=datetime.now()
    #print (today)
    # Get the current time
    t = datetime.time(datetime.now())
    print("The current time is", t)
    #weekday returns 0 (monday) through 6 (sunday)
    wd=date.weekday(today)
    #Days start at 0 for monday
    days= ["monday","tuesday","wednesday","thursday","friday","saturday","sunday"]
    print("Today is day number %d" % wd)
    print("which is a " + days[wd])


main()

Output:

The current time is 11:30:18.637930
Today is day number 5
which is a saturday
>>>

 

Previous :Math Inbuilt Functions
Next :Random Inbuilt Functions

Python Basic Programming Tutorial

Python Introduction     Getting started in Python Programming      Python propgramming fundamentals     Python Operators    Python If Condition     Python for loop    Python range construct      Python While loop    break and continue statements     Different looping techniques     Python List     Python String     Python Functions    Python Inbuilt Functions     Python Recursion     Using Python Library     Python Tuples     Python Dictionary     Python Sets     Python Strings     Python Exception Handling     Python Data File Handling