askvity

How do you set a time range in Python?

Published in Date Ranges 3 mins read

To set a time range in Python, you primarily use the date_range() function from the pandas library. This allows you to generate a sequence of dates between a start and end date.

Using pandas.date_range()

The pandas.date_range() function is specifically designed for creating sequences of dates. Here’s how to use it and some key parameters:

  • Basic Syntax: pd.date_range(start, end, freq)

    • start: Specifies the start date of the range.
    • end: Specifies the end date of the range.
    • freq: (Optional) Determines the frequency of the date range (e.g., 'D' for daily, 'W' for weekly, 'M' for monthly). If not specified, the default is daily.

Examples:

Here are some examples to illustrate how date_range() is used:

  1. Daily Date Range:

    import pandas as pd
    
    date_range_daily = pd.date_range(start='2023-01-01', end='2023-01-05')
    print(date_range_daily)

    This will output a sequence of dates: DatetimeIndex(['2023-01-01', '2023-01-02', '2023-01-03', '2023-01-04', '2023-01-05'], dtype='datetime64[ns]', freq='D')

  2. Weekly Date Range:

    import pandas as pd
    
    date_range_weekly = pd.date_range(start='2023-01-01', end='2023-01-22', freq='W')
    print(date_range_weekly)

    This will output weekly dates, starting on Sunday: DatetimeIndex(['2023-01-01', '2023-01-08', '2023-01-15', '2023-01-22'], dtype='datetime64[ns]', freq='W-SUN')

  3. Monthly Date Range:

    import pandas as pd
    
    date_range_monthly = pd.date_range(start='2023-01-01', end='2023-05-01', freq='M')
    print(date_range_monthly)

    This will output the last day of each month within the given range: DatetimeIndex(['2023-01-31', '2023-02-28', '2023-03-31', '2023-04-30'], dtype='datetime64[ns]', freq='M')

Key Considerations:

  • Flexibility: You can use strings like '2023-01-01' or datetime objects for start and end parameters.
  • Frequency Options: You can specify more frequency settings such as 'H' for hourly, 'T' or 'min' for minutes, 'S' for seconds and many more based on your requirements.
  • Time zones: You can also handle time zones using the tz parameter in date_range().

In summary, the date_range() function from pandas is the go-to method for creating time ranges in Python, offering significant flexibility with frequency and time parameters.

Related Articles