Python Date and Time
Python’s datetime module provides functions to work with dates and times. Below are some common patterns for date and time handling in Python.
The following table describes various formats with their results:
Format Example | Result |
---|---|
datetime.datetime.now().strftime(‘%m/%d/%Y’) | 05/29/2015 |
datetime.datetime.now().strftime(‘%A, %d %B %Y’) | Friday, 29 May 2015 |
datetime.datetime.now().strftime(‘%Y-%m-%d’) | 2024-07-06 |
datetime.datetime.now().strftime(‘%I:%M %p’) | 5:50 AM |
datetime.datetime.now().strftime(‘%H:%M:%S’) | 14:30:06 |
datetime.datetime.now().strftime(‘%B %d’) | May 29 |
datetime.datetime.now().strftime(‘%Y-%m-%dT%H:%M:%S.%f%z’) | 2024-07-06T14:30:06.123456+00:00 |
Example:
import datetime
# Get the current date and time in default format
default = datetime.datetime.now()
# Get the current date and time in custom format
custom = default.strftime(“%m/%d/%Y %I:%M %p”)
# Print the current date and time in both formats
print(“Current Date and Time (Default):”, default)
print(“Current Date and Time (Custom):”, custom)
#Output:
#Current Date and Time (Default): 2024-08-27 14:30:06.123456
#Current Date and Time (Custom): 08/27/2024 02:30 PM
Format Codes:
1. %d: Day of the month (1-31)
2. %A: Full weekday name
3. %b: Abbreviated month name
4. %B: Full month name May
5. %m: Month as a zero-padded number
6. %y: Two-digit year
7. %Y: Four-digit year
8. %H: 24-hour clock hour
9. %I: 12-hour clock hour
10. %M: Minutes
11. %S: Seconds
12. %p: AM/PM
13. %f: Microseconds
14. %z:UTC offset
Example 2:
birthdate_str = ’19-08-2002′
#Converting string into date object
birthdate = datetime.datetime.strptime(birthdate_str, “%d-%m-%Y”)
#getting today’s date
today = datetime.datetime.today()
#Calculating age
age = today.year – birthdate.year – ((today.month, today.day) < (birthdate.month, birthdate.day))
print(f”Your age is: {age} years”) #Output: Your age is: 22 years
Explanation:
age = today.year – birthdate.year – ((today.month, today.day) < (birthdate.month, birthdate.day))
Lets, breakdown age calculation formula:
1. today.year – birthdate.year
This simply subtracts the birth year from the current year to get the basic age in years.
For example, if today is 2024-09-13 and the birthdate is 2002-08-19, this part will give 2024 – 2002 = 22.
But this alone might not be accurate, because the person’s birthday might not have occurred yet in the current year.
2. ((today.month, today.day) < (birthdate.month, birthdate.day))
This is a comparison between two tuples:
(today.month, today.day) gives the current month and day (for example, (9, 13) for September 13).
(birthdate.month, birthdate.day) gives the birth month and day (for example, (8, 19) for August 19).
The comparison checks if the current month and day come before the birth month and day in the same year.
If the current date is before the birthday in the current year, this comparison will return True (which is equivalent to 1 in Python).
If the current date is on or after the birthday, the comparison will return False (which is equivalent to 0).
3. – ((today.month, today.day) < (birthdate.month, birthdate.day))
This part subtracts 1 if the person hasn’t had their birthday yet in the current year, or 0 if they already had their birthday.
This adjustment ensures the age calculation is correct. If the birthday hasn’t happened yet this year, the age is one year less than the simple subtraction of years.
Task:
1. Current Date and Time:
Print the current date and time to the console using DateTime.Now.
2. Date Formatting:
Print the current date in the format “yyyy-MM-dd” (e.g., “2024-07-06”).
3. Date Comparison:
Create two DateTime objects representing different dates.
Compare these dates to determine which one is earlier or if they are equal.
4. Date Manipulation:
Create a DateTime object representing today’s date.
Add 5 days to this date and print the result.
5. Age Calculation:
Ask the user to enter their birthdate.
Calculate their age based on the current date and print it.
6. You are given a list of individuals with their birthdates in different formats:
people = [
[‘John’, ’12-12-2000′],
[‘Jane’, ’12-6-2002′],
[‘Jack’, ’12-01-1992′]
]
Write a Python program that:
1. Converts the birthdates strings into a proper datetime format.
2. Calculates the age of each individual.
3. Determines who is the youngest and the oldest among the individuals.
4. Output each person’s name and age.
5. Output the name of the youngest and the oldest person.
Expected Output:
John is 23 years old.
Jane is 21 years old.
Jack is 31 years old.
The youngest person is Jane with age 21 years.
The oldest person is Jack with age 31 years.
# Create a set and access the 3rd element
numbers = {2, 4, 10, 5, 15, 3}
print(f”The third element: {numbers[2]}”)
Explanation:
● numbers = {2, 4, 10, 5, 15, 3}: This initializes a set with 6 integer values: 2, 4, 10, 5, 15, and 3.
● print(f”The third element: {numbers[2]}”): This prints the 3rd element of the set. In Python, sets are zero-indexed, meaning the index starts from 0. Therefore, numbers[2] refers to the 3rd element, which is 10.
Set Operations
1. Union: Combines elements from two sets, removing duplicates.
set1 = {1, 2, 3}
set2 = {3, 4, 5}
union_set = set1.union(set2)
print(union_set) # Output: {1, 2, 3, 4, 5}
2. Intersection: Returns elements common to both sets.
intersection_set = set1.intersection(set2)
print(intersection_set) # Output: {3}
3. Difference: Returns elements present in the first set but not in the second.
difference_set = set1.difference(set2)
print(difference_set) # Output: {1, 2}
4. Symmetric Difference: Returns elements in either set, but not in both.
symmetric_difference_set = set1.symmetric_difference(set2)
print(symmetric_difference_set) # Output: {1, 2, 4, 5}
Task:
1. Integer set:
Create a set of integers with values from 1 to 5.
Print all elements of the set.
2. String set:
Create a set of strings with the names of three fruits.
Print all elements of the set.
3. Double set:
Create a set of doubles with any 4 double values.
Print the sum of all elements in the set.
4. Boolean set:
Create a set of booleans with alternating true and false values.
Print all elements of the set.