Search code examples
pythonpython-2.7datetimepytzpython-datetime

Adjust adjust time in by adding seconds for both remote location and current location with pytz & datetime


I'm trying to add some seconds onto a time but I can't find how to do it at all.

add_seconds = 952
cur_time = datetime.now(pytz.timezone('Europe/London')).strftime("%H%M")

The code above is what I am using to get a current, correct time for London, UK and I am trying to add add_seconds onto it which should give me a different time to the current time in London

If I can convert the cur_time then I can do what I need to do by:

cur_time =+ add seconds
m, s = divmod(cur_time, 60)
h, m = divmod(m, 60)
print "%02d:%02d:%02d" % (h, m, s)

However, I would also want to print the adjusted local time of where the script is being ran.


Solution

  • You mean using datetime.timedelta?

    import datetime
    import pytz
    
    add_seconds = datetime.timedelta(seconds=952)
    cur_time = datetime.datetime.now(pytz.timezone('Europe/London'))
    cur_time += add_seconds
    
    print(cur_time)
    

    This way you end up with a new datetime.datetime object with the extra time added in.