Python: Extract year, month, date and time using Lambda
8. Datetime Extractor Lambda
Write a Python program to extract year, month, date and time using Lambda.
Sample Solution:
Python Code :
# Import the 'datetime' module to work with date and time
import datetime
# Get the current date and time using 'datetime.datetime.now()' and store it in the variable 'now'
now = datetime.datetime.now()
# Display the current date and time stored in 'now'
print(now)
# Define a lambda function 'year' to extract the year from a given datetime object 'x'
year = lambda x: x.year
# Define a lambda function 'month' to extract the month from a given datetime object 'x'
month = lambda x: x.month
# Define a lambda function 'day' to extract the day from a given datetime object 'x'
day = lambda x: x.day
# Define a lambda function 't' to extract the time from a given datetime object 'x'
t = lambda x: x.time()
# Print the year extracted from the current datetime object 'now'
print(year(now))
# Print the month extracted from the current datetime object 'now'
print(month(now))
# Print the day extracted from the current datetime object 'now'
print(day(now))
# Print the time extracted from the current datetime object 'now'
print(t(now))
Sample Output:
2020-01-15 09:03:32.744178 2020 1 15 09:03:32.744178
For more Practice: Solve these Related Problems:
- Write a Python program to extract the weekday name from a given datetime object using lambda.
- Write a Python program to format a datetime object into a custom string format (e.g., 'DD-MM-YYYY HH:MM:SS') using lambda.
- Write a Python program to extract the hour and minute components from a datetime object using lambda.
- Write a Python program to check whether a given datetime falls on a weekend using lambda.
Python Code Editor:
Have another way to solve this solution? Contribute your code (and comments) through Disqus.
Previous: Write a Python program to find if a given string starts with a given character using Lambda.
Next: Write a Python program to check whether a given string is number or not using Lambda.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics