How to use date and time in Python

Published on Aug. 22, 2023, 12:15 p.m.

To get today’s date and time in Python, you can use the datetime module. Specifically, you can use the datetime.now() function to get the current date and time with microseconds precision.

Here’s an example:

import datetime

now = datetime.datetime.now()

print("Current date and time:", now)

This will output something like:

Current date and time: 2023-03-25 05:20:12.507684

If you only want to get the current date, without the time component, you can use the date() method on the datetime object:

import datetime

today = datetime.datetime.now().date()

print("Today's date:", today)

This will output something like:

Today's date: 2023-03-25

How to format time output in Python

To format time output in Python, you can use the strftime method from the datetime module. This method allows you to format a datetime object as a string using a specific format string. Here’s an example of how to format the current time as a string in a specific format:

import datetime

now = datetime.datetime.now()
formatted_time = now.strftime("%Y-%m-%d %H:%M:%S")

print("Formatted time:", formatted_time)

This will output something like:

Formatted time: 2023-03-25 05:32:19

In this example, %Y, %m, %d, %H, %M, and %S are format codes that represent year (4 digits), month (2 digits), day (2 digits), hour (24-hour format), minute, and second, respectively. You can use any combination of these codes, along with other characters and symbols, to create the desired format for your date and time string.

To calculate the elapsed time between two dates or times in Python

To calculate the elapsed time between two dates or times in Python, you can use the datetime module. Here’s an example:

import datetime

t1 = datetime.datetime.now()
t2 = t1 - datetime.timedelta(minutes=1)

delta = t1 - t2

print("Time elapsed:", delta)

This will output something like:

Time elapsed: 0:01:00.000120

In this example, t1 represents the current time, and t2 is the time one minute earlier. timedelta is used to calculate the difference between these two times. The resulting datetime.timedelta object includes the elapsed time in days, seconds, and microseconds.

You can then extract the elapsed time in specific units using the days, seconds, and microseconds attributes of the timedelta object. For example:

print("Time elapsed:", delta.seconds, "seconds")

This will output something like:

Time elapsed: 60 seconds

To change the date format of a Pandas DataFrame column containing datetime values

To change the date format of a Pandas DataFrame column containing datetime values, you can use the strftime() method from the datetime module. Here’s an example:

import pandas as pd
import datetime

df = pd.DataFrame({'date': ['2022-01-01', '2022-02-01', '2022-03-01']})
df['date'] = pd.to_datetime(df['date'])

df['formatted_date'] = df['date'].apply(lambda x: x.strftime('%Y/%m/%d'))

print(df)

This will output:

        date formatted_date
0 2022-01-01     2022/01/01
1 2022-02-01     2022/02/01
2 2022-03-01     2022/03/01

In this example, we first convert the ‘date’ column to a datetime data type using pd.to_datetime(). Then, we use the apply() function to apply a lambda function that formats each datetime value using the %Y/%m/%d format string.

You can replace %Y/%m/%d with any other valid format string, depending on the format you want to use.

convert a string to a datetime object using the strptime() function from the datetime module

In native Python, you can convert a string to a datetime object using the strptime() function from the datetime module. Here’s an example:

import datetime

date_string = '2022-02-01'
date_obj = datetime.datetime.strptime(date_string, '%Y-%m-%d')

print(date_obj)

This will output:

2022-02-01 00:00:00

In this example, we pass the date string and a format string to the datetime.strptime() function, which returns a datetime object representing the same date and time. The format string specifies the format of the input date string. In this case, %Y-%m-%d means that the input string should be in the format of ‘year-month-day’.

You can also convert a list or a tuple of strings to a list or tuple of datetime objects using the same datetime.strptime() function. For example:

import datetime

date_strings = ('2022-01-01', '2022-02-01', '2022-03-01')
date_objs = [datetime.datetime.strptime(ds, '%Y-%m-%d') for ds in date_strings]

print(date_objs)

This will output:

[datetime.datetime(2022, 1, 1, 0, 0), datetime.datetime(2022, 2, 1, 0, 0), datetime.datetime(2022, 3, 1, 0, 0)]

In this example, we create a tuple of strings representing dates, and then use a list comprehension to convert the tuple to a list of datetime objects using datetime.strptime() and the same format string as before.

To convert a string to a datetime object in Python using Pandas

To convert a string to a datetime object in Python using Pandas, you can use the to_datetime() function. Here’s an example:

import pandas as pd

date_string = '2022-02-01'
date_obj = pd.to_datetime(date_string)

print(date_obj)

This will output:

2022-02-01 00:00:00

In this example, we pass the date string to the to_datetime() function, which returns a datetime object representing the same date and time. You can then use this datetime object to perform various operations on the date and time, such as formatting it or calculating elapsed time.

You can also convert a column of strings in a Pandas DataFrame to a column of datetime objects using the same to_datetime() function. For example:

import pandas as pd

df = pd.DataFrame({'date': ['2022-01-01', '2022-02-01', '2022-03-01']})
df['date'] = pd.to_datetime(df['date'])

print(df)

This will output:

        date
0 2022-01-01
1 2022-02-01
2 2022-03-01

In this example, we create a Pandas DataFrame with a column called ‘date’ containing strings representing dates. We then apply the to_datetime() function to this column and reassign the result to the same ‘date’ column, effectively converting the column from a string data type to a datetime data type.