Python datetime lambda

Do not miss this exclusive book on Binary Tree Problems. Get it now for free.

In this article, we have explained how to extract date and time in Python using 4 different Lambda functions.

Table of contents:

  1. Approach 1: Lambda printing complete date and time
  2. Approach 2: No need to save datetime object
  3. Approach 3: Lambda function to extract info from datetime object
  4. Approach 4: Lambda function to return info directly

Approach 1: Lambda printing complete date and time

The idea is to get the get time and date in the form of a datetime object using datetime.now() function. We use lambda to extract different information like year and month.

Following Python code extracts the date and time using lambda:

import datetime
now = datetime.datetime.now()
print("Date/Time: ", now)
f = lambda x: print("Year: ", x.year, ", Month: ", x.month, ", Day: ", x.day, ", Time: ", x.time())
f(now)

Output:

Date/Time:  2022-11-27 19:00:37.765894
Year:  2022 , Month:  11 , Day:  27 , Time:  19:00:37.765894

Approach 2: No need to save datetime object

In this case, we directly use the datetime.now() function within the lambda to extract different information.

import datetime
f = lambda : print("Year: ", datetime.datetime.now().year, 
", Month: ", datetime.datetime.now().month, 
", Day: ", datetime.datetime.now().day, 
", Time: ", datetime.datetime.now().time())
f()

Output:

Year:  2022 , Month:  11 , Day:  27 , Time:  19:22:28.441521

Approach 3: Lambda function to extract info from datetime object

In this, we define different functions using lambda that can extract different information from datetime object.

import datetime
now = datetime.datetime.now()
print("Date/ Time: ", now)
year = lambda x: x.year
month = lambda x: x.month
day = lambda x: x.day
time = lambda x: x.time()
print("Year: ", year(now))
print("Month: ", month(now))
print("Day: ", day(now))
print("Time: ", time(now))

Output:

Date/ Time:  2022-11-27 19:05:59.423488
Year:  2022
Month:  11
Day:  27
Time:  19:05:59.423488

Approach 4: Lambda function to return info directly

In this case, we define functions using lambda which return the required date value (month, year and others) directly. This does not require a datetime object to be passed to the lambda function.

import datetime
year = lambda : datetime.datetime.now().year
month = lambda : datetime.datetime.now().month
day = lambda : datetime.datetime.now().day
time = lambda : datetime.datetime.now().time()
print("Year: ", year())
print("Month: ", month())
print("Day: ", day())
print("Time: ", time())

Output:

Year:  2022
Month:  11
Day:  27
Time:  19:05:23.505240

With this article at OpenGenus, you must have the complete idea of using lambda to get current date and time.

Sign up for FREE 3 months of Amazon Music. YOU MUST NOT MISS.