How to get strftime 7 hours in the past? - python

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)

Related

UTC representation of midnight on the UTC day that was in progress 24 hours ago in python

I want to format timestamp to day -1 but require a format
I am getting day-1 exactly minus 24 hrs but I need from midnight onwards
from datetime import datetime,timedelta
import pytz
partdate=datetime.today().strftime('%Y-%m-%d %H:%M:%S')
# print(partdate)
# import pytz
tzinfo=pytz.timezone('US/Eastern')
# print(tzinfo)
x=(datetime.now() + timedelta(days=-1)) # Here
tzinfo=pytz.timezone('US/Eastern')
pardate1=tzinfo.localize(datetime.now()+timedelta(days=-1),is_dst=None)
print(pardate1)
#print('x----->',x)
#print('timevalue',tzinfo)
# yesterday = datetime.today() - timedelta(days = 1 )
# print(yesterday)
output is 2022-08-13 20:39:26.232974-04:00
But required output is 2022-08-13T00:00:000Z
IIUC, you want date/time now in a certain time zone, subtract one day, then convert to UTC, then 'floor' that date/time to midnight.
Here's a step-by-step example how you can do that. Note that I use zoneinfo since pytz is deprecated and time zone name "America/New_York" as "US/Eastern" is obsolte as well.
from datetime import datetime, timedelta
from zoneinfo import ZoneInfo
now = datetime.now(ZoneInfo("America/New_York"))
daybefore = now - timedelta(days=1)
daybefore_UTC = daybefore.astimezone(ZoneInfo("UTC"))
daybefore_UTC_midnight = daybefore_UTC.replace(hour=0, minute=0, second=0, microsecond=0)
print(now)
print(daybefore_UTC_midnight)
# 2022-08-15 03:38:42.006215-04:00
# 2022-08-14 00:00:00+00:00

Adding hours and days to the python datetime

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)

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 datetime add

I have a datetime value in string format. How can I change the format from a "-" separated date to a "." separated date. I also need to add 6 hours to let the data be in my time zone.
s = '2013-08-11 09:48:49'
from datetime import datetime,timedelta
mytime = datetime.strptime(s,"%Y-%m-%d %H:%M:%S")
time = mytime.strftime("%Y.%m.%d %H:%M:%S")
dt = str(timedelta(minutes=6*60)) #6 hours
time+=dt
print time
print dt
I get the following result where it adds the six hours at the end and not to the nine:
2013.08.11 09:48:496:00:00
6:00:00
You are adding the string representation of the timedelta():
>>> from datetime import timedelta
>>> print timedelta(minutes=6*60)
6:00:00
Sum datetime and timedelta objects, not their string representations; only create a string after summing the objects:
from datetime import datetime, timedelta
s = '2013-08-11 09:48:49'
mytime = datetime.strptime(s, "%Y-%m-%d %H:%M:%S")
mytime += timedelta(hours=6)
print mytime.strftime("%Y.%m.%d %H:%M:%S")
This results in:
>>> from datetime import datetime, timedelta
>>> s = '2013-08-11 09:48:49'
>>> mytime = datetime.strptime(s, "%Y-%m-%d %H:%M:%S")
>>> mytime += timedelta(hours=6)
>>> print mytime.strftime("%Y.%m.%d %H:%M:%S")
2013.08.11 15:48:49
However, you probably want to use real timezone objects instead, I recommend you use the pytz library:
>>> from pytz import timezone, utc
>>> eastern = timezone('US/Eastern')
>>> utctime = utc.localize(datetime.strptime(s, "%Y-%m-%d %H:%M:%S"))
>>> local_tz = utctime.astimezone(eastern)
>>> print mytime.strftime("%Y.%m.%d %H:%M:%S")
2013.08.11 15:48:49
This will take into account daylight saving time too, for example.

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