Adelin
Adelin

Reputation: 18971

Python datetime conversion from int datetime and vise versa

I am new to Pythong and trying to convert DateTime in Python to int then convert int back again to DateTime, but I am missing 2 hours exactly which I don't know why.

Code:

import datetime
import calendar
import time

def test_time_conversion():
        now = datetime.datetime.now().replace(microsecond=0)
        time_now_decimal = calendar.timegm(now.timetuple())
        dt = datetime.datetime.fromtimestamp(time_now_decimal)
        time_expected_decimal = calendar.timegm(dt.replace(microsecond=0).timetuple())
        print("\n")
        print(now)
        print(time_now_decimal)
        print(dt)
        print(time_expected_decimal)

Output:

2021-11-17 14:49:39
1637160579
2021-11-17 16:49:39
1637167779

Upvotes: 0

Views: 565

Answers (2)

h4z3
h4z3

Reputation: 5468

You're missing 2 hours, not 2 minutes. It's because of timezone conversion.

datetime.now() returns timezone-naive (no timezone info saved) local time. Because of lack of timezone info, timestamp will get converted without adjusting, thus assuming the time is UTC.

Two fixes:

  • Either pass timezone you want as argument to datetime.now(). Docs. E.g. datetime.now(timezone.utc)
  • Or use datetime.utcnow() to get (still timezone-naive) UTC before converting. This approach is not recommended because timezone-naive datetime is often interpreted as local time - mentioned in all utc-but-naive methods in docs

Upvotes: 0

deceze
deceze

Reputation: 522145

datetime.now() returns a local, naïve timestamp, i.e. 14:49 is your current wall clock time. timegm interprets this time as being in UTC (Greenwich mean time). And 14:49 in your timezone and 14:49 in Greenwich appears to have a 2 hour difference.

Upvotes: 1

Related Questions