SoFunction
Updated on 2024-11-13

Python processing date methods detailed book (30 methods)

Using the time module to display the current date and time

import time
from time import gmtime, strftime
 
t = ()  
print ((t))  # Sun May 7 09:30:37 2017
print(strftime("%a, %d %b %Y %H:%M:%S +0000", gmtime()))  # Sun, 07 May 2017 04:00:37 +0000
print(strftime("%A", gmtime()))  # Sunday
print(strftime("%D", gmtime()))  # 05/07/17
print(strftime("%B", gmtime()))  # May
print(strftime("%y", gmtime()))  # 17
 
# Convert seconds into GMT date
print(strftime("%a, %d %b %Y %H:%M:%S +0000", gmtime(1234567890)))  # Fri, 13 Feb 2009 23:31:30 +0000

II. Converting days, hours and minutes to seconds

SECONDS_PER_MINUTE = 60
SECONDS_PER_HOUR = 3600
SECONDS_PER_DAY = 86400
 
# of days, hours, minutes, seconds entered
days = int(input("Enter number of Days: "))
hours = int(input("Enter number of Hours: "))
minutes = int(input("Enter number of Minutes: "))
seconds = int(input("Enter number of Seconds: "))
 
# Calculated
total_seconds = days * SECONDS_PER_DAY
total_seconds = total_seconds + ( hours * SECONDS_PER_HOUR)
total_seconds = total_seconds + ( minutes * SECONDS_PER_MINUTE)
total_seconds = total_seconds + seconds
 
# Results
print("Total number of seconds: ","%d"%(total_seconds))
'''
Enter number of Days: 5
Enter number of Hours: 36
Enter number of Minutes: 24
Enter number of Seconds: 15
Total number of seconds: 563055
'''

Using Pandas to Get the Current Date and Time

import pandas as pd
print(())  # 2018-01-19 16:08:28.393553
print(().date())  # 2018-01-19
print(().year)  # 2018
print(().month)  # 1
print(().day)  # 19
print(().hour)  # 16
print(().minute)  # 8
print(().second)  # 28
print(().microsecond)  # 394553

Fourth, the string will be converted to date and time objects

from datetime import datetime
from dateutil import parser

d1 = "Jan 7 2015  1:15PM"
d2 = "2015 Jan 7  1:33PM"

# If you know date format
date1 = (d1, '%b %d %Y %I:%M%p')
print(type(date1))  # class ''
print(date1)  # 2015-01-07 13:15:00

# If you don't know date format
date2 = (d2)
print(type(date2))  # class ''
print(date2)  # 2015-01-07 13:33:00

V. Getting the current time in milliseconds

import time
 
milliseconds = int(round(() * 1000))
print(milliseconds)  # 1516364270650

Get the current date and time in MST, EST, UTC, GMT and HST.

from datetime import datetime
from pytz import timezone
 
mst = timezone('MST')
print("Time in MST:", (mst))  # Time in MST: 2017-01-19 06:06:14.495605-07:00
est = timezone('EST')
print("Time in EST:", (est))  # Time in EST: 2017-01-19 08:06:14.496606-05:00
utc = timezone('UTC')
print("Time in UTC:", (utc))  # Time in UTC: 2017-01-19 13:06:14.496606+00:00
gmt = timezone('GMT')
print("Time in GMT:", (gmt))  # Time in GMT: 2017-01-19 13:06:14.496606+00:00
hst = timezone('HST')
print("Time in HST:", (hst))  # Time in HST: 2017-01-19 03:06:14.497606-10:00

VII. Getting the day of the week from a given date

import datetime
 
dayofweek = (2010, 6, 16).strftime("%A")
print(dayofweek)  # Wednesday

# weekday() method: 0 for Monday, 6 for Sunday
print("weekday():", (2010, 6, 16).weekday())  # weekday(): 2
 
# isoweekday() method: 1 for Monday, 7 for Sunday
print("isoweekday()", (2010, 6, 16).isoweekday())  # isoweekday() 3
 
dayofweek = ().strftime("%A")
print(dayofweek)  # Friday
print("weekday():", ().weekday())  # weekday(): 4
print("isoweekday()", ().isoweekday())  # isoweekday(): 5

VIII. Calculating the time difference between two date-time objects

import datetime
from datetime import timedelta
 
datetimeFormat = '%Y-%m-%d %H:%M:%S.%f'
date1 = '2016-04-16 10:01:28.585'
date2 = '2016-03-10 09:56:28.067'
diff = (date1, datetimeFormat)\
    - (date2, datetimeFormat)
 
print("Difference:", diff)  # Difference: 37 days, 0:05:00.518000
print("Days:", )  # Days: 37
print("Microseconds:", )  # Microseconds: 518000
print("Seconds:", )  # Seconds: 300

IX. Adding 5 minutes to a Unix timestamp

import datetime
import calendar
 
future = () + (minutes=5)
print((()))  # 1621069619

X. Iterating through a series of dates

import datetime

start = ("21-06-2020", "%d-%m-%Y")
end = ("05-07-2020", "%d-%m-%Y")
date_generated = [start + (days=x) for x in range(0, (end - start).days)]

for date in date_generated:
    print(("%d-%m-%Y"))

XI. Change of time from Paris to New York

import pendulum
 
in_paris = (2016, 8, 7, 22, 24, 30, tz='Europe/Paris')
print(in_paris)  # 2016-08-07T22:24:30+02:00
 
in_us = in_paris.in_timezone('America/New_York')
print(in_us)  # 2016-08-07T16:24:30-04:00

XII. Using Python to get the last 7 working days

from datetime import date
from datetime import timedelta
 
today = ()
 
for i in range(7):
    d = today - timedelta(days=i)
    if () < 5:
        print(d)

XIII. Age deduction from today's date and a person's birthday

from datetime import date
 
def calculate_age(born):
    today = ()
    try:
        birthday = (year=)
    except ValueError:
        birthday = (year=, month= + 1, day=1)
    if birthday > today:
        return  -  - 1
    else:
        return  - 
 
print(calculate_age(date(2001, 3, 1)))

XIV. Getting the first Tuesday of the month

import calendar
from datetime import datetime
 
c = (firstweekday=)
monthcal = (().year, ().month)
#Python white learning exchange group: 153708845
try:
    tues = [day for week in monthcal for day in week if
            () ==  and  == ().month][0]
    print(tues)
except IndexError:
    print('No date found')

XV. Convert integers to date objects

from datetime import datetime

i = 1545730073
timestamp = (i)

print(timestamp)  # 2018-12-25 14:57:53
print(type(timestamp))

XVI. Current date minus N number of days

from datetime import datetime, timedelta

d = () - timedelta(days=5)
print(d)

XVII. Comparing two dates

import datetime

a = (2020, 12, 31, 23, 59, 59)
b = (2020, 11, 30, 23, 59, 59)

print(a < b)
print(a > b)

Extracting years from datetime objects

import datetime
 
year = ().year
print(year)

XIX. Finding the day of the week according to the date

import pendulum
 
dt = ('2021-05-18')
print(dt.day_of_week)  # 2
 
dt = ('2021-05-01')
print(dt.day_of_week) # 6
 
dt = ('2021-05-21')
print(dt.day_of_week) # 5

XX. Getting the date 7 days ago from the current date

from datetime import datetime, timedelta
 
now = ()
 
for x in range(7):
    d = now - timedelta(days=x)
    print(("%Y-%m-%d"))

XXI. Convert the difference between two date-time objects to seconds

import datetime
 
time1 = ('19 01 2021', '%d %m %Y')
time2 = ('25 01 2021', '%d %m %Y')
 
difference = time2 - time1
print(difference)  # 6 days, 0:00:00
 
seconds = difference.total_seconds()
print(seconds)  # 518400.0

XXII. Getting the Nth Friday of any month

import calendar

# Take the third Friday of May, 2021.
c = (firstweekday=)
year = 2021
month = 5
n = 2  # Take the third
monthcal = (year, month)
 
try:
    third_friday = [
        day for week in monthcal 
            for day in week if
                () ==  and  == month
    ][n]
    print(third_friday)  # 2021-05-21
except IndexError:
    print('No date found')

XXIII. Obtaining dates based on the number of weeks

import datetime
from  import relativedelta
 
week = 25
year = 2021
date = (year, 1, 1) + relativedelta(weeks=+week)
print(date)  # 2021-06-25

XXIV. Working days for obtaining specific dates

import datetime
 
print((2020, 5, 15).isocalendar()[2])  # 5

Create a DateTime that is 15 minutes old.

import datetime
#Python white learning exchange group: 153708845
dt = () - (minutes=15)
print(dt)  # 2021-05-15 22:25:55.897365

XXVI. Getting the start and end of the week from a specific date

import pendulum
 
dt = (2012, 9, 5)
 
start = dt.start_of('week')
print(start.to_datetime_string())  # 2012-09-03 00:00:00
 
end = dt.end_of('week')
print(end.to_datetime_string())  # 2012-09-09 23:59:59

XXVII. Difference between two dates (in seconds)

from datetime import datetime
#Python white learning exchange group: 153708845
fmt = '%Y-%m-%d %H:%M:%S'
d1 = ('2020-01-01 17:31:22', fmt)
d2 = ('2020-01-03 17:31:22', fmt)
 
days_diff = d2 - d1
print(days_diff.days * 24 * 60 * 60)  # 172800

XXVIII. Get yesterday's date in this format MMDDYYY

from datetime import date, timedelta
 
yesterday = () - timedelta(days=1)
print(('%m%d%y'))  # 051421

XXIX. Get last Wednesday's date based on today's date

from datetime import date
from datetime import timedelta

today = ()

offset = (() - 2) % 7
wednesday = today - timedelta(days=offset)
print(wednesday)  # 2021-05-12

XXX. Print a list of all available time zones

import pytz

for i in pytz.all_timezones:
    print(i)

summarize

This article on the Python date processing method is introduced to this article, more related Python date processing method content please search for my previous articles or continue to browse the following related articles I hope that you will support me in the future more!