Python Date functions

Importing datetime library

from datetime import date
Today's date
from  datetime import date
dt = date.today() 
print(dt)    # 2019-09-16

Python date and time to get todays tomorrow yesterday dates by using relative delta for calculations

Getting day , month , year and weekday

Commonly used instances
from  datetime import date
print("Today day : ",date.today().day)
print("Today month : ",date.today().month)
print("Today year : ",date.today().year)
print("Today weekday : ",date.today().weekday())
Output
Today day :  16
Today month :  9
Today year :  2019
Today weekday :  0

Tomorrow

from datetime import timedelta,date,datetime
dt = date.today() + timedelta(days=1) # tomorrow 
print(dt)

Yesterday

dt = date.today() + timedelta(days=-1) # Yesterday

More Instance methods:

toodinal()Proleptic Gregorian ordinal of the date
timetuple()Details of date and time as a tuple
strftime()Date & time to String
strptime()String to datetime object
resolution()Minimum difference between String to datetime object
replace()Update date object with new parameters
max() & min()Maximum and Minimum representable date
isoweekday()Day of the week as integer
isocalendar()ISO year, ISO week number & ISO weekday
fromtimestamp()Getting date and time by using timestamp
fromordinal()Getting date by using ordinal
fromisoformat()Getting date by using iso fomat date string
Creating a date object
import datetime
dt=datetime.datetime(2019,5,24)
print(dt.day,dt.month,dt.year) # 24 5 2019 

Getting time

import time
h=time.strftime('%I') # getting local hour in 12 hours format as string 
h=int(h)*2 # to multiply the hour as integer 
print (h)

Getting Date and time

from datetime import datetime
now = datetime.now()
print(now) # present date and time 
# use different formats 
dt=datetime.strftime(now,'%Y/%m/%d : %H:%M:%S')
print(dt) 
Output
2021-12-22 06:27:52.051532
2021/12/22 : 06:27:52
Read more on strftime() formats to get hour minutes etc.

Creating Date time object.
import datetime
dt=datetime.datetime(2019,5,24,14,52,53)
print(dt.day,dt.month,dt.year) # 24 5 2019 
print(dt.hour,dt.minute,dt.second)# 14 52 53
Output
24 5 2019
14 52 53
2nd Saturday Display 2nd and 4th Saturday of the month
calendarCalendar module to Create yearly or monthly Calendars
New YearShow Countdown and new year message
All timedelta objects relativedelta
Exercise on Date & time
Subscribe to our Youtube Channel here

Subscribe

* indicates required
Subscribe to plus2net

    plus2net.com



    Post your comments , suggestion , error , requirements etc here





    Python Video Tutorials
    Python SQLite Video Tutorials
    Python MySQL Video Tutorials
    Python Tkinter Video Tutorials
    We use cookies to improve your browsing experience. . Learn more
    HTML MySQL PHP JavaScript ASP Photoshop Articles FORUM . Contact us
    ©2000-2022 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer