3

I have a string timestamp. I want to convert it to seconds and then again later I want to convert that seconds into a timestamp. So for this, I converted the string to timestamp first then calculated seconds. Again I converted that seconds into a timestamp.

But converted timestamp is not matching with the original one. How can I fix this problem?

I used the below code for this conversion:

import datetime
import pandas as pd


def string_to_datetime(string):
    dv = [string]

    dv_series = pd.Series(dv)
    dv_to_datetime = pd.to_datetime(dv_series)
    dv_to_datetime_list = list(dv_to_datetime)

    return dv_to_datetime_list[0]


timestamp = ['2020-06-12T08:33:14']

timestamp = string_to_datetime(timestamp[0])
print('timestamp:')
print(timestamp)

timestamp_in_seconds = float((timestamp - datetime.datetime(1970, 1, 1)).total_seconds())

print('timestamp in seconds:')
print(timestamp_in_seconds)

print('Again converted to timestamp:')
print(datetime.datetime.fromtimestamp(timestamp_in_seconds))

The output of the above code is like below:

timestamp:
2020-06-12 08:33:14
timestamp in seconds:
1591950794.0
Again converted to timestamp:
2020-06-12 14:33:14
BC Smith
  • 727
  • 1
  • 7
  • 19
  • 1
    `fromtimestamp()` probably assumes an epoch in UTC and adjusts for your current time zone. – Mark Ransom Oct 11 '20 at 22:07
  • 1
    I think you need `print(datetime.datetime.utcfromtimestamp(timestamp_in_seconds))` – Chris Charley Oct 11 '20 at 22:09
  • have a look at the [datetime docs](https://docs.python.org/3/library/datetime.html#datetime.datetime.fromtimestamp) with focus on *naive* vs. *time zone aware*. In contrast to `pandas` datetime, Python's datetime has the (sometimes confusing) property of assuming *local time* by default (naive datetime case). pandas assumes UTC if no time zone / UTC offset is defined. – FObersteiner Oct 14 '20 at 08:24

1 Answers1

1

I got two solutions. Maybe it will be helpful for someone later.

solution_1 = datetime.datetime.fromtimestamp(timestamp_in_seconds, tz=pytz.UTC)


solution_2 = datetime.datetime.utcfromtimestamp(timestamp_in_seconds)

Timezone information is important during converting back to the original timestamp.

BC Smith
  • 727
  • 1
  • 7
  • 19
  • 1
    Python's datetime will by default assume you want *local time*. While your solution_1 is correct, the other is actually wrong but *showing* what you expect. [Don't use utcfromtimestamp](https://blog.ganssle.io/articles/2019/11/utcnow.html), it's just confusing. Better use e.g. `datetime.datetime.fromtimestamp(timestamp_in_seconds, tz=datetime.timezone.utc)`. – FObersteiner Oct 14 '20 at 08:21