Date time is one of the most important object in any programming language, we often use date time in different format for logging and tracking user activities, In this article you will learn how to handle date time in python
There are various date time format in python, depend on your requirement you can also manipulate format.
When you work with MySQL, you may need to insert current date from python code, following is the easiest and supported format for mysql database
We need to import following classes
from datetime import date from datetime import datetime
from datetime import date from datetime import datetime today=date.today() tdate = today.isoformat();
Now if you want to change the date format for display or any other requirement, for example if you want a format like year/dd/mm , you can write like example below
today=date.today() tdate = today.strftime("%Y/%d/%m") print(tdate) #year-dd-mm
date output will be like
Now if you want to get date with time, then use following code
date time result will be like
Get today's date object in python, then get day, month, year separately
from datetime import date # Get today's date object today = date.today() print("Current day:", today.day) print("Current month:", today.month) print("Current year:", today.year)
We can create python time object then can set different values from hour, minutes, seconds and milliseconds.
from datetime import time # time(hour = 0, minute = 0, second = 0) a = time() print("example 1 =", a) # time(hour, minute and second) b = time(10, 28, 55) print("example 2 =", b) # time(hour, minute and second) c = time(hour = 10, minute = 37, second = 46) print("example 3 =", c) # time(hour, minute, second, microsecond) d = time(10, 46, 19, 540010) print("example 4 =", d)
We also can combine date and time together using python datetime object .
from datetime import datetime #datetime(year, month, day) a = datetime(2020, 10, 28) print(a) # datetime(year, month, day, hour, minute, second, microsecond) b = datetime(2020, 10, 28, 19, 46, 55, 822350) print(b)
Here is how you can find difference between two dates, or two datatimes
from datetime import datetime, date // Date difference dt1 = date(2024, 10, 28) today = date.today() dateDiff = dt1 - today print("Date Difference", dateDiff) // datetime difference dtime1 = datetime(year = 2024, month = 10, day = 28, hour = 10, minute = 37, second = 55) dtime2 = datetime.now() datetimeDiff = dtime1 - dtime2 print("date time difference", datetimeDiff)
Date time is very commonly used object in any programming language, there are many different format of date and time, though with above information you will be able to manage most of your work, but if you want to know more about python date functions take a look at different date time format in python example .