Adding hours and days to the python datetime - python

I have a string in the following format
2021-05-06 17:30
How do I convert this to a python datetime and add a certain number of hours (e.g 4 hours)?
I also need to add a certain number of days to the string 2021-05-06

You can first parse the string to a datetime object, and then use a timedelta to add days, hours, etc. to the item.
from datetime import datetime, timedelta
dt = datetime.strptime('2021-05-06 17:30', '%Y-%m-%d %H:%M')
print(dt + timedelta(hours=4))

from datetime import datetime
from datetime import timedelta
origin_date = datetime.strptime("2021-05-06 17:30","%Y-%m-%d %H:%M")
three_hour_later = origin_date + timedelta(hours=3)
print(datetime.strftime(three_hour_later,"%Y-%m-%d %H:%M"))
Please check this link.
https://docs.python.org/3/library/datetime.html

Use the timedelta method available on datetime object to add days, hours, minutes or seconds to the date.
from datetime import datetime, timedelta
additional_hours = 4
additional_days = 2
old_date = datetime.strptime('2021-05-06 17:30', '%Y-%m-%d %H:%M')
new_date = old_date + timedelta(hours=additional_hours, days=additional_days)
print(new_date)

Related

python: How to calculate the new date knowing the number of hours passed since a base date?

I have a base date and an amount of passed hours since that date and want to calculate the new date. Here is the code:
import datetime
date_time_str = '1900-01-01 00:00:00.0'
date_time_obj = datetime.datetime.strptime(date_time_str, '%Y-%m-%d %H:%M:%S.%f')
passed_hour = 1047486
Can python achieve this automatically or I should do it manually?
You could use timedelta and add it to your existing datetime obj like this:
from datetime import datetime as dt, timedelta
date_time_str = '1900-01-01 00:00:00.0'
date_time_obj = dt.strptime(date_time_str, '%Y-%m-%d %H:%M:%S.%f')
passed_hour = 1047486
new_date_time_obj = date_time_obj + timedelta(hours=passed_hour)
print(new_date_time_obj)

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 Date In Future (x) Days, And Hours Left To Date?

How can I get date + time in the future from now by days? in this format: 10/08/2013 9:50 PM (dd/mm/yyyy) and also I would like Time left to date in hours for this new future date?
You need to use a datetime in combination with a timedelta object.
Like this:
from datetime import datetime, timedelta
dt = datetime.now()
td = timedelta(days=4)
# your calculated date
my_date = dt + td

How to get strftime 7 hours in the past?

I have a timestamp that is in a time zone 7 hours ahead of me. The timestamp is saved in the strftime format '%Y-%m-%d %H:%M'. How do I make this timestamp go 7 hours back?
Example: Timestamp right now: 2014-4-14 3:00. What I want: 2014-4-13 20:00
Another option:
>>> from datetime import datetime, timedelta
>>> str(datetime.strptime('2014-4-14 3:00', '%Y-%m-%d %H:%M') + \
timedelta(hours = -7))
'2014-04-13 20:00:00'
>>> datetime.strftime(datetime.now() + timedelta(hours=-7),'%Y-%m-%d %H:%M')
'2014-04-13 14:45'
I like the following if I have a datetime. Are you saying you only have string to work with?
import datetime
from dateutil.relativedelta import relativedelta
expires = datetime.datetime.now() - relativedelta(hours=7)

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