2

I have a naive timestamp which I need to convert to tzutc() timedate in order to calculate time delta.

I converted string to Date using

pd.Timestamp(x)

Then converted it to UTC using

pytz.utc.localize(x)

and got:

Timestamp('2019-01-09 00:00:00+0000', tz='UTC')

Problem is that the date I need to compare it to is

Timestamp('2018-06-07 18:13:53+0000', tz='tzutc()')

When comparing them I get

TypeError: Timestamp subtraction must have the same timezones or no timezones
Nazim Kerimbekov
  • 4,712
  • 8
  • 34
  • 58
Niv
  • 850
  • 1
  • 7
  • 22

1 Answers1

0

You can convert the timestamp to a datetime and back using the methods seen HERE.

Here is a method for converting a datetime from local time to UTC using pytz:

def LocalToUTC(dt):
    # Converts the local time to UTC

    localtz = get_localzone()

    if dt.tzinfo is None:
        localdt = localtz.localize(dt)
    else:
        localdt = dt.replace(tzinfo=localtz)

    utcdt = localdt.astimezone(pytz.UTC)
    return utcdt

Similarly here is a method for converting any timezone to UTC:

def TimezoneToUTC(dt, timezonestring):
    # Converts from a given timezone to UTC using the timezonestring
    # Example timezone string: 'Europe/Paris' OR 'America/New_York'

    fromtz = pytz.timezone(timezonestring)

    if dt.tzinfo is None:
        localdt = fromtz.localize(dt)
    else:
        localdt = dt.replace(tzinfo=fromtz)

    utcdt = localdt.astimezone(pytz.UTC)
    return utcdt

For a list of all timezone strings use:

>>> import pytz
>>> 
>>> for tz in pytz.all_timezones:
...     print tz
FutureTechLab
  • 142
  • 1
  • 10
  • Thank you @iridium237. Eventually thanks to your link I've devised another solution: I simply defined the time zone of the original date to tzutc Like this: pd.Timestamp(x,tz=tzutc()) Making both datestamps be in the same timezone. – Niv Jun 17 '19 at 09:55