Tuesday, 21 January 2020

Manipulate Date and Time in Python like Pro!!!

This is a cheat sheet I have created to  covers the most commonly used datetime related functions in Python. 
If you guys want something simple but practical with examples, take a look!
  1. Today’s date and time in different formats
  2. String to date conversion
  3. Difference in datetime calculation
  4. Datetime plus/minus a certain period of time
  5. Datetime comparison
  6. Time zones settings
Today’s date and time in different formats
Let’s warm up from the most basic.
 Below is the code that will print the current year, month, date, hour, minute, seconds and milliseconds.
This is very useful information but often we only need part of it. We can print the different parts below.
print(d.weekday()) #day of week - Monday is 0 and Sunday is 6
print(d.year)
print(d.month)
print(d.day)
print(d.hour)
print(d.minute)
print(d.second)
For certain  formats of the date/time we can use the below list to customize different date formats. This can also be considered a way of converting date to string. 
The full list can be found fom here 


print(d.strftime("%A %d/%m/%Y")) # date to string
String to date conversion
Below are examples showing two popular strings being converted to date format:
date_string = '2020-02-01 12:00PM'

print(datetime.strptime(date_string, '%Y-%m-%d %I:%M%p'))

date_string = '02/01/2020'

d = datetime.strptime(date_string, '%m/%d/%Y')

print(d)

Difference in datetime calculation
The example below prints the difference in days (for example today and February 1st, 2016):
from datetime import timedelta

d1 = datetime.now()

date_string = '2/01/2016'

d2 = datetime.strptime(date_string, '%m/%d/%Y')

print(d1 - d2)
We can also only print the difference of two datetimes in days, weeks or years, etc.
date_diff = (d - d2)/timedelta(days=1)
print('date_diff = {} days'.format(date_diff))

date_diff = (d - d2)/timedelta(weeks=1)
print('date_diff = {} weeks'.format(date_diff))

date_diff = (d - d2)/timedelta(days=365)
print('date_diff = {} years'.format(date_diff))
Datetime plus/minus a certain period of time
Let’s do some “time travel” by different time intervals of second, minute, hour, day, week or year:
print(d + timedelta(seconds=1)) # today + one second
print(d + timedelta(minutes=1)) # today + one minute
print(d + timedelta(hours=1)) # today + one hour
print(d + timedelta(days=1)) # today + one day
print(d + timedelta(weeks=1)) # today + one week
print(d + timedelta(days=1)*365) # today + one year
Datetime comparison
The comparisons between dates are straightforward with usual comparison symbols:

# d is no more than 6 years (assume each year has 365 days) after d2?    
print(d < (d2 +(timedelta(days=365*6)))) 

 # d is more than 6 years (assume each year has 52 weeks) after d2?
    print(d > (d2 +(timedelta(weeks=52*6))))

    print(d != d2) # d2 is not the same date as d?
    print(d == d2) # d2 is the same date as d
Time zones settings
And we can also compare time in different time zones, such as Toronto and India:

import pytz
timezone = pytz.timezone("America/Toronto")
dtz = timezone.localize(d)
print(dtz.tzinfo)
print(dtz)

india_dt = dtz.astimezone(pytz.timezone("Asia/Calcutta"))
print(india_dt)

print((dtz - india_dt)/timedelta(days=1)) # same datetime
For the list of all timezone
for tz in pytz.all_timezones:
    print(tz)

Thanks
Saurabh Sharma
Happy Coding !!!

No comments:

Post a Comment

Build a Custom Kernel Module for Android

Hi Guys!!!Hope you are doing well !!!. Today I will describe how you can write a custom kernel module(Hello world) for Android and load it a...