2

I would like to delete the timezone from my dateTime object.
Currently i have:
2019-02-21 15:31:37+01:00

Expected output:
2019-02-21 15:31:37

The code I have converts it to: 2019-02-21 14:31:37.

# Convert to date
mood['response_time'] = pd.to_datetime(mood['response_time'], utc=True)
# Remove +01:00
mood['response_time'] = mood['response_time'].dt.strftime('%Y-%m-%d %H:%M:%S')
TiFoxDutchZ
  • 45
  • 2
  • 7
  • So you just want to visually strip the TZ information or you want to convert to naive datetime or you want to preserve timezone? Things get a bit ambiguous time-wise when you do something like that. – Will Oct 28 '19 at 22:05
  • Just visually strip the TZ information, thanks. – TiFoxDutchZ Oct 28 '19 at 22:09
  • https://stackoverflow.com/questions/10944047/how-can-i-remove-a-pytz-timezone-from-a-datetime-object – Will Oct 28 '19 at 22:11
  • already tried that. This: mood = mood['response_time'].replace(tzinfo=None). Returns this: TypeError: replace() got an unexpected keyword argument 'tzinfo' – TiFoxDutchZ Oct 28 '19 at 22:19
  • make user mood["response_time"] is a datetime object first. – Will Oct 28 '19 at 22:27
  • That is what I did right? See my code... -> mood['response_time'] = pd.to_datetime(mood['response_time'], utc=True) – TiFoxDutchZ Oct 28 '19 at 22:35
  • `mood['response_time'].replace(tzinfo=None)` is not converting to DT first – Will Oct 29 '19 at 10:05

2 Answers2

4

Another possibility might be to take tz_localize(None). So for example this works:

mood = pd.DataFrame()

mood['response_time'] = ['2019-02-21 15:31:37+01:00']
# Convert to date
mood['response_time'] = pd.to_datetime(mood['response_time'])
# Remove +01:00
mood['response_time'] = mood['response_time'].dt.tz_localize(None)
mood['response_time'].iloc[0]
# => Timestamp('2019-02-21 15:31:37')
Matthias
  • 41
  • 2
3

In the first line, the parameter utc=True is not necessary as it converts the input to UTC (subtracting one hour in your case).

In the second line, I get an AttributeError: 'Timestamp' object has no attribute 'dt'. Be aware that to_datetime can return different objects depending on the input.

So the following works for me (using a Timestamp object):

mood['response_time'] = '2019-02-21 15:31:37+01:00'
# Convert to date
mood['response_time'] = pd.to_datetime(mood['response_time'])
# Remove +01:00
mood['response_time'] = mood['response_time'].strftime('%Y-%m-%d %H:%M:%S')
# -> '2019-02-21 15:31:37'
Gerd
  • 2,568
  • 1
  • 7
  • 20