How to minus time with Python - python

I'd like to get the time before X seconds before
datetime.time.now(). For example, if the time.now() is 12:59:00, and I minus 59, I want to get 12:00:00.
How can I do that?

You can use time delta like this:
import datetime
print datetime.datetime.now() - datetime.timedelta(minutes=59)

import datetime
datetime.datetime.now() - datetime.timedelta(seconds=59)
Should do the trick
You can read more about timedelta on the documentation:
class datetime.timedelta
A duration expressing the difference between
two date, time, or datetime instances to microsecond resolution.

You need to use timedelta
from datetime import timedelta, datetime
d = datetime.now()
d = d - timedelta(minutes=59)
print d

You can try dateutil:
datetime.datetime.now() + dateutil.relativedelta.relativedelta(second=-60)

Related

How to minus time that received from API server and current time in Python

Kindly help below my query:
I got an estimated time from API server like below:
2019-09-25T20:11:23+08:00
it seems like iso 8601 standard with timezone.
I would like to know how to calculate how many days, hours, minutes and seconds left from above value to the current time.
import datetime
Receved_time_frim_API = "2019-09-25T20:11:23+08:00"
Current_time = datetime.datetime.now()
left_days =
left_hour =
left_min =
left_sec =
Your time string contains timezone info. According to https://stackoverflow.com/a/13182163/12112986 it's easy to convert it to datetime object in python 3.7
import datetime
received = datetime.datetime.fromisoformat(Receved_time_frim_API)
In previous versions there is no easy oneliner to convert string with timezone to datetime object. If you're using earlier python version, you can try something crude, like
>>> date, timezone = Receved_time_frim_API.split("+")
>>> tz_hours, tz_minutes = timezone.split(":")
>>> date = datetime.datetime.strptime(date, "%Y-%m-%dT%H:%M:%S")
>>> date -= datetime.timedelta(hours=int(tz_hours))
>>> date -= datetime.timedelta(minutes=int(tz_minutes))
Note that this will work only in case of positive timezones
To substract two datetime objects use
td = date - Current_time
left_days = td.days
left_hour = td.seconds // 3600
left_min = (td.seconds//60)%60
left_sec = td.seconds % 60
Okay first you need to parse the Receved_time_frim_API into datetime format:
from dateutil import parser
Receved_time_frim_API = parser.parse("2019-09-25T20:11:23+08:00")
But you can't just substract this from your Current_time, because datetime.now() is not aware of a timezone:
from datetime import timezone
Current_time = datetime.datetime.now().replace(tzinfo=timezone.utc)
print (Current_time-Receved_time_frim_API)
The result is a datetime.timedelta

How can i add 7 hours into api_time? [duplicate]

I am able to get the current time as below:
from datetime import datetime
str(datetime.now())[11:19]
Result
'19:43:20'
Now, I am trying to add 9 hours to the above time, how can I add hours to current time in Python?
from datetime import datetime, timedelta
nine_hours_from_now = datetime.now() + timedelta(hours=9)
#datetime.datetime(2012, 12, 3, 23, 24, 31, 774118)
And then use string formatting to get the relevant pieces:
>>> '{:%H:%M:%S}'.format(nine_hours_from_now)
'23:24:31'
If you're only formatting the datetime then you can use:
>>> format(nine_hours_from_now, '%H:%M:%S')
'23:24:31'
Or, as #eumiro has pointed out in comments - strftime
Import datetime and timedelta:
>>> from datetime import datetime, timedelta
>>> str(datetime.now() + timedelta(hours=9))[11:19]
'01:41:44'
But the better way is:
>>> (datetime.now() + timedelta(hours=9)).strftime('%H:%M:%S')
'01:42:05'
You can refer strptime and strftime behavior to better understand how python processes dates and time field
This works for me working with seconds not hours and also using a function to convert back to UTC time.
from datetime import timezone, datetime, timedelta
import datetime
def utc_converter(dt):
dt = datetime.datetime.now(timezone.utc)
utc_time = dt.replace(tzinfo=timezone.utc)
utc_timestamp = utc_time.timestamp()
return utc_timestamp
# create start and end timestamps
_now = datetime.datetime.now()
str_start = str(utc_converter(_now))
_end = _now + timedelta(seconds=10)
str_end = str(utc_converter(_end))
This is an answer which is significant for nowadays (python 3.9 or later).
Use strptime to create a datetime object from the timestring. Add 9 hours with timedelta, and match the time format with the timestring you have.
from datetime import datetime, timedelta
from zoneinfo import ZoneInfo
time_format = "%H:%M:%S"
timestring = datetime.strptime(str(datetime.now() + timedelta(hours=9))[11:19], time_format)
#You can then apply custom time formatting as well as a timezone.
TIMEZONE = [Add a timezone] #https://en.wikipedia.org/wiki/List_of_tz_database_time_zones
custom_time_format = "%H:%M"
time_modification = datetime.fromtimestamp(timestring.timestamp(), ZoneInfo(TIMEZONE)).__format__(custom_time_format)
While I think it's more meaningful to apply a timezone, you don't necessarily need to, so you can also simply do that:
time_format = "%H:%M:%S"
timestring = datetime.strptime(str(datetime.now() + timedelta(hours=9))[11:19], time_format)
time_modification = datetime.fromtimestamp(timestring.timestamp())
datetime
https://docs.python.org/3/library/datetime.html
strftime-and-strptime-format-codes
https://docs.python.org/3/library/datetime.html#strftime-and-strptime-format-codes
timedelta
https://docs.python.org/3/library/datetime.html#datetime.timedelta
zoneinfo
https://docs.python.org/3/library/zoneinfo.html#module-zoneinfo

Python - get elapsed time using datetime

With the datetime module, I can get the current time, like so:
>>> datetime.now().strftime('%Y-%m-%d %H:%M:%S')
'2017-08-29 23:01:32'
I have access to the time at which a file was created, in the same format:
>>> data['created']
'2017-08-29 20:59:09'
Is there a way, using the datetime module, that I can calculate the time between the two, in hours?
Performing subtraction on two datetime objects will result in a timedelta. You can use datetime.strptime to get that second datetime object, access the seconds attribute of that timedelta and calculate the hours from there:
from datetime import datetime
...
file_created = datetime.strptime(data['created'], '%Y-%m-%d %H:%M:%S')
difference = (datetime.now() - file_created).seconds
print("Hours since creation: " + str(difference // 3600)) # 3600 seconds in 1 hour

How to subtract datetimes / timestamps in python

Seems like this should be so simple but for the life of me, I can't find the answer. I pull two datetimes/timestamps from the database:
2015-08-10 19:33:27.653
2015-08-10 19:31:28.209
How do I subtract the first from the second, preferably the result being in milliseconds? And yes, I have the date in there, too, because I need it to work at around midnight, as well.
Parse your strings as datetime.datetime objects and subtract them:
from datetime import datetime
d1 = datetime.strptime("2015-08-10 19:33:27.653", "%Y-%m-%d %H:%M:%S.%f")
d2 = datetime.strptime("2015-08-10 19:31:28.209", "%Y-%m-%d %H:%M:%S.%f")
print(d1 - d2)
Gives me:
0:01:59.444000
Also check out timedelta documentation for all possible operations.
you can do subtraction on 2 datetime objects to get the difference
>>> import time
>>> import datetime
>>>
>>> earlier = datetime.datetime.now()
>>> time.sleep(10)
>>> now = datetime.datetime.now()
>>>
>>> diff = now - earlier
>>> diff.seconds
10
convert your strings to datetime objects with time.strptime
datetime.strptime("2015-08-10 19:33:27.653", "%Y-%m-%d %H:%M:%S.%f")
timedelta.seconds does not represent the total number of seconds in the timedelta, but the total number of seconds modulus 60.
Call the function timedelta.total_seconds() instead of accessing the timedelta.seconds property.
For python 3.4, first you'd need to convert the strings representing times into datetime objects, then the datetime module has helpful tools work with dates and times.
from datetime import datetime
def to_datetime_object(date_string, date_format):
s = datetime.strptime(date_string, date_format)
return s
time_1 = '2015-08-10 19:33:27'
time_2 = '2015-08-10 19:31:28'
date_format = "%Y-%m-%d %H:%M:%S"
time_1_datetime_object = to_datetime_object(time_1, date_format)
time_2_datetime_object = to_datetime_object(time_2, date_format)
diff_time = time_1_datetime_object - time_2_datetime_object

How to add hours to current time in python

I am able to get the current time as below:
from datetime import datetime
str(datetime.now())[11:19]
Result
'19:43:20'
Now, I am trying to add 9 hours to the above time, how can I add hours to current time in Python?
from datetime import datetime, timedelta
nine_hours_from_now = datetime.now() + timedelta(hours=9)
#datetime.datetime(2012, 12, 3, 23, 24, 31, 774118)
And then use string formatting to get the relevant pieces:
>>> '{:%H:%M:%S}'.format(nine_hours_from_now)
'23:24:31'
If you're only formatting the datetime then you can use:
>>> format(nine_hours_from_now, '%H:%M:%S')
'23:24:31'
Or, as #eumiro has pointed out in comments - strftime
Import datetime and timedelta:
>>> from datetime import datetime, timedelta
>>> str(datetime.now() + timedelta(hours=9))[11:19]
'01:41:44'
But the better way is:
>>> (datetime.now() + timedelta(hours=9)).strftime('%H:%M:%S')
'01:42:05'
You can refer strptime and strftime behavior to better understand how python processes dates and time field
This works for me working with seconds not hours and also using a function to convert back to UTC time.
from datetime import timezone, datetime, timedelta
import datetime
def utc_converter(dt):
dt = datetime.datetime.now(timezone.utc)
utc_time = dt.replace(tzinfo=timezone.utc)
utc_timestamp = utc_time.timestamp()
return utc_timestamp
# create start and end timestamps
_now = datetime.datetime.now()
str_start = str(utc_converter(_now))
_end = _now + timedelta(seconds=10)
str_end = str(utc_converter(_end))
This is an answer which is significant for nowadays (python 3.9 or later).
Use strptime to create a datetime object from the timestring. Add 9 hours with timedelta, and match the time format with the timestring you have.
from datetime import datetime, timedelta
from zoneinfo import ZoneInfo
time_format = "%H:%M:%S"
timestring = datetime.strptime(str(datetime.now() + timedelta(hours=9))[11:19], time_format)
#You can then apply custom time formatting as well as a timezone.
TIMEZONE = [Add a timezone] #https://en.wikipedia.org/wiki/List_of_tz_database_time_zones
custom_time_format = "%H:%M"
time_modification = datetime.fromtimestamp(timestring.timestamp(), ZoneInfo(TIMEZONE)).__format__(custom_time_format)
While I think it's more meaningful to apply a timezone, you don't necessarily need to, so you can also simply do that:
time_format = "%H:%M:%S"
timestring = datetime.strptime(str(datetime.now() + timedelta(hours=9))[11:19], time_format)
time_modification = datetime.fromtimestamp(timestring.timestamp())
datetime
https://docs.python.org/3/library/datetime.html
strftime-and-strptime-format-codes
https://docs.python.org/3/library/datetime.html#strftime-and-strptime-format-codes
timedelta
https://docs.python.org/3/library/datetime.html#datetime.timedelta
zoneinfo
https://docs.python.org/3/library/zoneinfo.html#module-zoneinfo

Categories