简体   繁体   中英

Python - How can I create a range of equally spaced timestamps with a resolution of milliseconds by specifying a frequency?

I would like to create a Python list containing a range of equally spaced timestamps with a resolution of milliseconds by specifying the following inputs:

  • Start date in the format dd/mm/yyyy hh:MM:ss.sss .
  • End date in the format dd/mm/yyyy hh:MM:ss.sss .
  • Frequency of data in Hz.

How can it be done?

You can make use of the Pandas .date_range() function (see docs here ), since it returns the range of equally spaced time points by specifying a start , end and freq . See the example below (note that the start and end dates are initially strings):

# Import the required libraries
from datetime import datetime
import pandas as pd

# Select your inputs
start_date_string = "14/10/2021 17:37:19.000"   # String
end_date_string = "14/10/2021 17:38:20.000"     # String
frequency = 64                                  # In Hz

# Convert the strings of dates into the Python datetime format
start_datetime = datetime.strptime(start_date_string, '%d/%m/%Y %H:%M:%S.%f')
end_datetime = datetime.strptime(end_date_string, '%d/%m/%Y %H:%M:%S.%f')

# Create a range of dates
index = pd.date_range(start = start_datetime, end = end_datetime,
                      freq="{}".format(1000/frequency)+"L")

The key in this answer is the freq parameter inside the .date_range() function, since it selects the frequency of the returned data (see here for a list of frequency aliases). There is a bit of fine-tunning to be done because our frequency is specified in Hz, but this can perfectly be done with freq="{}".format(1000/frequency)+"L" .

Where index is our required output:

DatetimeIndex([       '2021-10-14 17:37:19', '2021-10-14 17:37:19.015625',
               '2021-10-14 17:37:19.031250', '2021-10-14 17:37:19.046875',
               '2021-10-14 17:37:19.062500', '2021-10-14 17:37:19.078125',
               '2021-10-14 17:37:19.093750', '2021-10-14 17:37:19.109375',
               '2021-10-14 17:37:19.125000', '2021-10-14 17:37:19.140625',
               ...
               '2021-10-14 17:38:19.859375', '2021-10-14 17:38:19.875000',
               '2021-10-14 17:38:19.890625', '2021-10-14 17:38:19.906250',
               '2021-10-14 17:38:19.921875', '2021-10-14 17:38:19.937500',
               '2021-10-14 17:38:19.953125', '2021-10-14 17:38:19.968750',
               '2021-10-14 17:38:19.984375',        '2021-10-14 17:38:20'],
              dtype='datetime64[ns]', length=3905, freq='15625U')

From here, you can proceed to transform it into for example a list by using index.tolist() .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM