'Pandas create a date range with UTC time

I have this code to create a date range dataframe

dates_df = pd.date_range(start='01/01/2022', end='02/02/2022', freq='1H')

The problem is that the time is not UTC. It is dtype='datetime64[ns] instead of dtype='datetime64[ns, UTC]

How can I generate the date range in UTC without having the generated time change?



Solution 1:[1]

pass the parameter timezone = 'utc' otherwise the result of date_range() is timezone neutral and can be interpreted as your desired timezone

dates_df = pd.date_range(start='01/01/2022', end='02/02/2022', freq='1H',tz='UTC')

output:

>>>
DatetimeIndex(['2022-01-01 00:00:00+00:00', '2022-01-01 01:00:00+00:00',
               ...               
               '2022-02-01 23:00:00+00:00', '2022-02-02 00:00:00+00:00'],
              dtype='datetime64[ns, UTC]', length=769, freq='H')

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 eshirvana