0

What I am trying to do is to get the current datetime of a place using an API with python and extract datetime from it. The code that I have is:

import requests
import json
from datetime import datetime
import time

def get_current_time_from_api():
    response = (requests.get("http://worldtimeapi.org/api/ip")).json()
    return response["datetime"]

the_time = get_current_time_from_api()

When I print the response using print(the_time), the response that gets returned is:

2020-05-06T10:04:51.368291+05:45

Then, I tried getting the converting the string to datetime using the function datetime.strptime(the_time, "%X) to get the time, I get the error ValueError: time data '2020-05-06T10:09:52.009222+05:45' does not match format '%X' So, what went wrong and how can I do things like this when the time is parsed from the string?

if(time == "10:00:00 pm"):
    #do something here
else:
    difference_in_minutes = "10:00:00" - current_time
    time.sleep(difference_in_minutes * 100) #sleeping for that many seconds
    #do stuff when the time is 10 pm

2 Answers2

1

I think you may be looking for the fromisoformat method. Try this:

import datetime as dt
dt.datetime.fromisoformat(the_time).strftime('%X')

Output:
'21:37:54'
Trace Malloc
  • 394
  • 1
  • 3
  • 5
0
from datetime import datetime
from dateutil.relativedelta import relativedelta

datetime_obj = datetime.strptime(
    '2020-05-06T10:04:51.368291+05:45', # your datetime string
    '%Y-%m-%dT%H:%M:%S.%f%z' # format of datetime
)

# this is how you can add a day to date_object
new_date = datetime_obj + relativedelta(days=1)

This is wrong time == "10:00:00 pm" you should use datetime_objects to compare, like:

if new_date > datetime_obj: # this is true.
    # You can do things here
    print("Yes")

# if(time == "10:00:00 pm"), should be done like this:
if datetime_obj.time().hour == 10 and datetime_obj.time().min == 10:
    pass

See for datetime formatting : https://docs.python.org/3/library/datetime.html#strftime-and-strptime-format-codes

relativedelta: https://dateutil.readthedocs.io/en/stable/relativedelta.html

thisshri
  • 632
  • 8
  • 18
  • It seems like there is no module named dateutil from the error that says: `ModuleNotFoundError: No module named 'dateutil' ` – Mukesh Aryal May 06 '20 at 05:21
  • Fix this https://stackoverflow.com/questions/20853474/importerror-no-module-named-dateutil-parser – thisshri May 06 '20 at 10:06
  • How do I find the difference in minutes between 10 pm and current time? @thisshri – Mukesh Aryal May 13 '20 at 06:21
  • @MukeshAryal you can do this by `relativedelta(datetime1, datetime2).minutes` Please see the documentation https://dateutil.readthedocs.io/en/stable/relativedelta.html – thisshri May 17 '20 at 06:57