Home > Net >  Pandas create a date range with UTC time
Pandas create a date range with UTC time

Time:03-27

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?

CodePudding user response:

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')
  • Related