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.
Related
How can I convert string 2021-09-30_1 to datetime 2021/09/30 00:00, which means that from the last string we have to substract one to get the hour.
I tried datetime.strptime(date, '%Y %d %Y %I')
datetime.strptime if to define the timestamp from a string, the format should match the provided one. datetime.strftime (note the f) is to generate a string from a datetime object.
You can use:
datetime.strptime(date, '%Y-%m-%d_%H').strftime('%Y/%m/%d %H:%M')
output: '2021/09/30 01:00'
in case the _x defines a delta:
from datetime import datetime, timedelta
d, h = date.split('_')
d = datetime.strptime(d, '%Y-%m-%d')
h = timedelta(hours=int(h))
(d-h).strftime('%Y/%m/%d %H:%M')
output: '2021/09/29 23:00'
Considering the _1 is hour and appears in al of your data (The hour part takes value between [1, 24]), your format was wrong.
For reading the date from string you'll need format it correctly:
from datetime import datetime, timedelta
date = "2021-09-30_1"
date_part, hour_part = date.split("_")
date_object = datetime.strptime(date_part, '%Y-%m-%d') + timedelta(hours=int(hour_part) - 1)
Now you have the date object. And you can display it as:
print(date_object.strftime('%Y/%m/%d %H:%M'))
from datetime import datetime
raw_date = "2021-09-30_1"
date = raw_date.split("_")[0]
parsed_date = datetime.strptime(date, '%Y-%m-%d')
formated_date = parsed_date.strftime('%Y/%m/%d %H:%M')
strptime is used for parsing string and strftime for formating.
Also for date representation you should provide format codes for hours and minutes as in:
formated_date = parsed_date.strftime('%Y/%m/%d %H:%M')
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)
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
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)
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