45.Date and Time in Python

Python has a module named datetime to work with dates and times.

Commonly used classes in the datetime module are:
date Class
time Class
datetime Class
timedelta Class

date class

>>>import datetime 
>>>d = datetime.date(2019, 4, 13) 
>>>print(d)
2019-04-13
We can use today() method defined in the date class to get a date object containing the current local date.
>>> import datetime 
>>> datetime_object = datetime.date.today()
>>> print("current date=",datetime_object)
2020-09-11

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 at UTC. You can convert a timestamp to date using fromtimestamp() method.  
>>>from datetime import date 
>>> date.fromtimestamp(1583562786) 
print("Date =", timestamp) 

When you run this, the output will be:Date =2020-03-07 

Print today's year, month and day
We can get year, month, day, day of the week etc. from the date object easily. Here's how: 
>>>from datetime import date 
>>> today = date.today() 
>>>print("Current year:", today.year) 
2020
>>>print("Current month:", today.month) 
9
>>>print("Current day:", today.day)
11

Difference between two dates 
>>> from datetime import date
>>> d1 = date(year = 2018, month = 7, day = 12)
>>> d2 = date(year = 2020, month = 12, day = 23)
>>> print(d2-d1)
895 days, 0:00:00

time class

Time object to represent time 

from datetime  import time 
# time(hour = 0, minute = 0, second = 0) 
>>>t= time() 
>>>print("t=", t )
t = 00:00:00

# time(hour, minute and second)
>>>t = time(11, 34, 56) 
>>>print("t =", t) 
t = 11:34:56

# time(hour, minute and second) 
>>>t = time(hour = 11, minute = 34, second = 56) 
>>>print("t =", t) 
t = 11:34:56

# time(hour, minute, second, microsecond) 
>>>t= time(11, 34, 56, 234566) 
>>>print("t =", t) 
t = 11:34:56.234566


Print hour, minute, second and microsecond

Once you create a time object, you can easily print its attributes such as hour, minute etc. 
>>>from datetime import time 
>>>a = time(11, 34, 56) 
>>>print("hour =", a.hour) 
11
>>>print("minute =", a.minute) 
34
>>>print("second =", a.second) 
56
>>>print("microsecond =", a.microsecond)
0

datetime class

The datetime module has a class named datetime class that can contain information from both date and time objects.
>>> from datetime import datetime 
>>> dt=datetime(2020,11,18)
>>> print(dt)
2020-11-18 00:00:00
>>> dt=datetime(2020, 9, 11, 23, 55, 59, 342380)
>>> print(dt)
2020-09-11 23:55:59.342380

Print year, month, hour, minute and timestamp 
>>>from datetime import datetime 
>>>dt = datetime(2020, 9, 11, 23, 55, 59, 342380) 
>>>print("year =", a.year) 
2020
>>>print("month =", a.month) 
9
>>>print("day=",a.day)
11
>>>print("hour =", a.hour) 
23
>>>print("minute =", a.minute) 
55
>>>print("second =", a.second)
59
>>>print("timestamp =", a.timestamp())
1599848759.34238

Difference between two dates and time
>>> d1 = datetime(year = 2018, month = 7, day = 12, hour = 7, minute = 9, second = 33)
>>> d2 = datetime(year = 2020, month = 6, day = 10, hour = 5, minute = 55, second = 13)
>>> print(d2-d1)
698 days, 22:45:40

timedelta class

Difference between two timedelta objects 
>>> from datetime import timedelta
>>> t1 = timedelta(weeks = 1, days = 2, hours = 1, seconds = 30)
>>> t2 = timedelta(days = 3, hours = 12, minutes = 4, seconds = 55)
>>> print(t1-t2)
5 days, 12:55:35

Here, we have created two timedelta objects t1 and t2, and their difference is printed on the screen.

Printing negative timedelta object 
>>>from datetime import timedelta  
>>> t1=timedelta(seconds=53)
>>> t2=timedelta(seconds=55)
>>> print(t2-t1)
0:00:02
>>> print(t1-t2)
-1 day, 23:59:58
>>> print(abs(t1-t2))
0:00:02

Time duration in seconds

You can get the total number of seconds in a timedelta object using total_seconds() method. 
>>>from datetime import timedelta 
>>> t = timedelta(days = 4, hours = 2, seconds = 34, microseconds = 235673)
>>> t.total_seconds()
352834.235673

Note:You can also find sum of two dates and times using + operator. Also, you can multiply and divide a timedelta object by integers and floats.
>>> print(t/2)
2 days, 1:00:17.117836
>>> print(t*2)
8 days, 4:01:08.471346

Formatting date and time
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.

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.
>>> from datetime import datetime
>>> dt=datetime.now()
>>> print(dt)
2020-09-11 19:05:29.739075
>>> dt.strftime("%H:%M:%S")
'19:05:29'
>>> dt.strftime("%m/%d/%Y, %H:%M:%S")
'09/11/2020, 19:05:29'
>>> dt.strftime("%d/%m/%Y, %H:%M:%S")
'11/09/2020, 19:05: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.

%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 - minute [00, 01, ..., 58, 59]
%S - second [00, 01, ..., 58, 59]

string to date time object

The strptime() method creates a datetime object from a given string (representing date and time).
>>> print(datetime.strptime("11 September, 2020","%d %B, %Y"))
2020-09-11 00:00:00

The strptime() method takes two arguments:
  • a string representing date and time
  • format code equivalent to the first argument
By the way, %d, %B and %Y format codes are used for day, month(full name) and year respectively.

How to get current date and time  in Python?

There are a number of ways you can take to get the current date. We will use the date class of the datetime module to accomplish this task.
Example 1:Get today's date from datetime 
from datetime import date
today = date.today() 
print("Today's date:", today)
output:
Today's date: 2023-03-21 
2: Current date in different formats
from datetime import date
today = date.today()
# dd/mm/YY
d1 = today.strftime("%d/%m/%Y")
print("d1 =", d1)

# Textual month, day and year
d2 = today.strftime("%B %d, %Y")
print("d2 =", d2)

# mm/dd/y
d3 = today.strftime("%m/%d/%y")
print("d3 =", d3)

# Month abbreviation, day and year
d4 = today.strftime("%b-%d-%Y")
print("d4 =", d4)
outputs
d1 = 12/09/2020
d2 = September 12, 2020
d3 = 09/12/20
d4 = Sep-12-2020

Example 3: Get the current date and time
from datetime import datetime 
 # datetime object containing current date and time 
now = datetime.now() 
 print("now =", now) 
 # dd/mm/YY H:M:S 
dt_string = now.strftime("%d/%m/%Y %H:%M:%S")
print("date and time =", dt_string)
output
now = 2020-09-12 00:14:44.264780
date and time = 12/09/2020 00:14:44

Example 4: Current time using datetime object
from datetime import datetime
now = datetime.now()
current_time = now.strftime("%H:%M:%S")
print("Current Time =", current_time)
output
Current Time = 00:23:28
Example 5: Current time using time module
You can also get the current time using time module.
import time
t = time.localtime()
current_time = time.strftime("%H:%M:%S", t)
print(current_time)
output
08:15:58

Comments

Popular posts from this blog

Python For Machine Learning - CST 283 - KTU Minor Notes- Dr Binu V P

46.Classes and Objects in Python- Accessors and mutators

KTU Python for machine learning Sample Question Paper and Answer Key Dec 2020