0

I'm new to python and I need to convert the air_time variable to local machine time or the current_time variable to GMT and then subtract one from other in this script but don't know how to do it.

from datetime import datetime

air_time_GMT = '2020-08-05 13:30:00'
air_time = datetime.strptime(air_time_GMT, '%Y-%m-%d %H:%M:%S')
current_time = datetime.now()

time_remaining = air_time - current_time

print(time_remaining)
Rezwan
  • 17
  • 1
  • 9

2 Answers2

1

here's a way how you could do it with some explanations in the comments:

from datetime import datetime, timezone

air_time_GMT = '2020-08-05 13:30:00'

# Python will assume your input is local time if you don't specify a time zone:
air_time = datetime.strptime(air_time_GMT, '%Y-%m-%d %H:%M:%S')
# ...so let's do this:
air_time = air_time.replace(tzinfo=timezone.utc) # using UTC since it's GMT
       
# again, if you don't supply a time zone, you will get a datetime object that
# refers to local time but has no time zone information:
current_time = datetime.now()

# if you want to compare this to a datetime object that HAS time zone information,
# you need to set it here as well. You can set local time zone via
current_time = current_time.astimezone()

print(current_time)
print(air_time-current_time)
>>> 2020-08-05 14:11:45.209587+02:00 # note that my machine is on UTC+2 / CEST
>>> 1:18:14.790413

You should notice two things here I think.

  • For one, Python by default assumes a datetime object belongs to local time (OS time zone setting) if it is naive (no time zone information).
  • Second, you cannot compare naive datetime objects (no time zone / UTC offset defined) to aware datetime objects (time zone information given).

[datetime module docs]

FObersteiner
  • 22,500
  • 8
  • 42
  • 72
0

The command you are looking for is datetime.utcnow(). If you use this instead of datetime.now(), the script will use the current GMT time instead of your current time zone/machine time.

Please note: As you can see in MrFuppes answer, you need to be cautious wrt. time-zone awareness. However, if you keep all time objects naive and in UTC, the simple approach with datetime.utcnow() should be fine.

Franz
  • 357
  • 3
  • 11