-1

I think this is a simple problem, but I am struggling tremendously... I need to subtract two datetimes. One is naive and one is aware but I can not for the life of me convert one to the other.

How do I convert one of these datetimes to the other to allow subtraction?

Example code below:

now_time = str(pd.Timestamp("now"))
current_time = datetime.strptime(now_time, "%Y-%m-%d %H:%M:%S.%f")
x = df.at[0,1]
x = datetime.strptime(x, "%Y-%m-%d %H:%M:%S.%f%z")
print(current_time)
print(x)
print(current_time-x)

returns

2020-04-06 19:29:58.239641
2020-04-06 22:50:22.577561+00:00
Traceback (most recent call last):
  File "main.py", line 416, in <module>
    print(current_time-x)
TypeError: can't subtract offset-naive and offset-aware datetimes

andrew852
  • 25
  • 5
  • _How do I convert one of these datetimes to the other to allow subtraction?_ Have you tried anything, done any research? It took me less than a minute to find these two SO questions: [How to make an unaware datetime timezone aware in python](https://stackoverflow.com/questions/7065164/how-to-make-an-unaware-datetime-timezone-aware-in-python), [Converting timezone-aware datetime to local time in Python](https://stackoverflow.com/questions/5452555/converting-timezone-aware-datetime-to-local-time-in-python) – AMC Apr 07 '20 at 01:29

1 Answers1

0

So, you either need to make the first date aware or the second date naive.

current_time = datetime.datetime.now().astimezone()

or

x = datetime.strptime(x, "%Y-%m-%d %H:%M:%S.%f")
Eric Truett
  • 2,970
  • 1
  • 16
  • 21