fromtimestamp() Function Of Datetime.date Class in Python


The fromtimestamp() function of the Python datetime.date class is useful for converting a timestamp into a date object. A timestamp essentially denotes the duration since the epoch (which took place on January 1, 1970, 00:00:00 UTC). To help you understand the fromtimestamp() function's practical uses, we'll go over the syntax and coding practices involved in utilizing it in this blog article. We'll also include different Python code samples.

Syntax

datetime.date.fromtimestamp(timestamp)

The method returns a date object that represents the timestamp and only requires a single input, the timestamp value in seconds. You must use the class name to access the fromtimestamp() function since it is a class method of the datetime.date class.

Algorithm

The algorithm for the fromtimestamp() function can be described in the following steps −

  • Parse a timestamp value as an argument.

  • Utilize the datetime.fromtimestamp() method to convert the epoch timestamp to a object representing datetimes

  • Extract the year, month, and day values from the datetime object and instantiate a date object with these extracted values.

Example

import datetime

# create a timestamp value
timestamp = 1609459200
date_obj = datetime.date.fromtimestamp(timestamp)

# print the date object
print(date_obj)

Output

2021-01-01

To utilize the date class, we import the datetime module. Generate the timestamp value 1609459200, which corresponds to UTC 00:00:00 on January 1, 2021. Use the date class's fromtimestamp() function, passing the timestamp value as an input. The method pulls the year, month, and day values from the timestamp value before converting it to a datetime object. After that, it produces a date object that was made using the retrieved information. The date obj variable is used to hold the returned date object and the date object is printed at last displaying the value 2021-01-01.

A more practical-oriented example would be as follows.

Imagine you have a CSV file containing a dataset of financial transactions, each of which has a timestamp in Unix format (i.e., seconds since the epoch). To make a summary report that displays the total amount of transactions for each day, extract the date info from each transaction.

Example

import pandas as pd
import datetime

# mock dataframe with transaction data
data = {
   'timestamp': [1609459200, 1609459200, 1609545600, 1609545600, 1609632000], 'amount': [100.0, 200.0, 300.0, 400.0, 500.0]
}
df = pd.DataFrame(data)
# dict to accumulate transaction amounts by date
daily_totals = {}

# iterate over the transactions and accumulate totals by date
for index, row in df.iterrows():
   date = datetime.date.fromtimestamp(row['timestamp'])
   daily_totals[date] = daily_totals.get(date, 0) + row['amount']

# print generated summary report
print('Date\tTotal Amount')
print('-------------------')
for date, total in sorted(daily_totals.items()):
   print('{}\t${:,.2f}'.format(date.strftime('%Y-%m-%d'), total))

Output

Date	Total Amount
-------------------
2021-01-01	$300.00
2021-01-02	$700.00
2021-01-03	$500.00

Here, the transaction timestamp and amount should be placed in two separate columns of a fake dataframe that you first generate using a Python dictionary. In order to group the transaction totals by date, we then build an empty dictionary. Following that, we use the iterrows() method to loop through the data frame, the fromtimestamp() function to extract the date information, and the transaction amount to update the daily totals dictionary. Finally, after sorting the elements in the daily totals dictionary by date and structuring the result as a table with the date and total amount columns, we print the summary report.

Applications

  • Converting timestamp values from databases to date objects.

  • Processing log files that contain timestamp values.

  • Converting epoch time values to date objects.

Conclusion

We looked at the Python datetime.date class's fromtimestamp() method in this blog article. In addition to discussing the function's syntax and methodology, we also included a Python code sample to show how to use it. Many of the potential uses for this function were also covered. Your ability to utilize the fromtimestamp() method to change timestamp values into date objects in your own Python scripts should have improved with the exercises from this tutorial.

Updated on: 18-Apr-2023

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements