How to add time to a time string - python

I would like to add a certain time to a formatted time string in python. For this I tried the following
from datetime import datetime, timedelta
timestemp_Original = '2021-07-13T00:15:00Z'
timestemp_Added1 = '2021-07-13T00:15:00Z' + timedelta(minutes=15)
timestemp_Added2 = timestemp_Original + datetime.timedelta(hours=0, minutes=15)
but this leads to error messages (I took it from here How to add hours to current time in python and Add time to datetime). Can aynone tell me how to do this?

First, You need to convert str to datetime with a specific format of string_date and then use timedelta(minutes=15).
from datetime import datetime, timedelta
timestemp_Original = '2021-07-13T00:15:00Z'
timestemp_Added1 = datetime.strptime(timestemp_Original, "%Y-%m-%dT%H:%M:%SZ") + timedelta(minutes=15)
print(timestemp_Added1)
# If you want to get as original format
print(timestemp_Added1.strftime("%Y-%m-%dT%H:%M:%SZ"))
# 2021-07-13T00:30:00Z
2021-07-13 00:30:00

Related

strptime() error - Time from sensor with more than 24 hours (e.g. 24:01:53)

I am using datetime.strptime() to convert a string containing time and date from a sensor into a datetime object.
The code sometimes fails. Minimal example:
datetime.strptime('1/9/2021 24:01:53', '%d/%m/%Y %H:%M:%S')
Output error:
ValueError: time data '1/9/2021 24:01:53' does not match format '%d/%m/%Y %H:%M:%S'
I am guessing this has to do with the fact that the time is more than 23:59:59 - which seems to me a non-realistic time (I would think that 1/9/2021 24:01:53 could potentially be 2/9/2021 00:01:53 - a time format which I have never seen).
Is this a non-standard way of representing time or possibly a hardware/software issue with the sensor acquisition system? If it is a different way of representing time, how can I convert it to a standard datetime object?
Kind regards,
D.F.
If the hour exceeds 23 in a variable representing time, a good option is to create a timedelta from it, which you can then add to a datetime object. For given example that might look like
from datetime import datetime, timedelta
def custom_todatetime(s):
"""
split date/time string formatted as 'DD/MM/YYYY hh:mm:ss' into date and time parts.
parse date part to datetime and add time part as timedelta.
"""
parts = s.split(' ')
seconds = sum(int(x) * 60 ** i for i, x in enumerate(reversed(parts[1].split(':'))))
return datetime.strptime(parts[0], "%d/%m/%Y") + timedelta(seconds=seconds)
s = '1/9/2021 24:01:53'
print(custom_todatetime(s))
# 2021-09-02 00:01:53
Note: conversion of hh:mm:ss to seconds taken from here - give a +1 there if helpful.

How to add a certain time to a datetime?

I want to add hours to a datetime and use:
date = date_object + datetime.timedelta(hours=6)
Now I want to add a time:
time='-7:00' (string) plus 4 hours.
I tried hours=time+4 but this doesn't work. I think I have to int the string like int(time) but this doesn't work either.
Better you parse your time like below and access datetime attributes for getting time components from the parsed datetime object
input_time = datetime.strptime(yourtimestring,'yourtimeformat')
input_seconds = input_time.second # for seconds
input_minutes = input_time.minute # for minutes
input_hours = input_time.hour # for hours
# Usage: input_time = datetime.strptime("07:00","%M:%S")
Rest you have datetime.timedelta method to compose the duration.
new_time = initial_datetime + datetime.timedelta(hours=input_hours,minutes=input_minutes,seconds=input_seconds)
See docs strptime
and datetime format
You need to convert to a datetime object in order to add timedelta to your current time, then return it back to just the time portion.
Using date.today() just uses the arbitrary current date and sets the time to the time you supply. This allows you to add over days and reset the clock to 00:00.
dt.time() prints out the result you were looking for.
from datetime import date, datetime, time, timedelta
dt = datetime.combine(date.today(), time(7, 00)) + timedelta(hours=4)
print dt.time()
Edit:
To get from a string time='7:00' to what you could split on the colon and then reference each.
this_time = this_time.split(':') # make it a list split at :
this_hour = this_time[0]
this_min = this_time[1]
Edit 2:
To put it all back together then:
from datetime import date, datetime, time, timedelta
this_time = '7:00'
this_time = this_time.split(':') # make it a list split at :
this_hour = int(this_time[0])
this_min = int(this_time[1])
dt = datetime.combine(date.today(), time(this_hour, this_min)) + timedelta(hours=4)
print dt.time()
If you already have a full date to use, as mentioned in the comments, you should convert it to a datetime using strptime. I think another answer walks through how to use it so I'm not going to put an example.

How to convert strftime or string format to timestamp/Date in python?

I am very new to Python coding. I was trying to get the start and end date of a month and then compare it with another date column in the same excel.
I only need the date in mm/dd/yy format but do not need the time.
The final_month_end_date is basically a string format which I compare with an actual date but it gives me an error saying
"TypeError: Cannot compare type 'Timestamp' with type 'str'"
I have also tried .timestamp() function but of no use.
How can I resolve this problem?
import datetime as dt
import strftime
now1 = dt.datetime.now()
current_month= now1.month
current_year= now1.year
month_start_date= dt.datetime.today().strftime("%Y/%m/01")
month_end_date= calendar.monthrange(current_year,current_month)[1]
final_month_end_date= dt.datetime.today().strftime("%Y/%m/"+month_end_date)
To convert a string to a DateTime object use datetime.strptime. Once you have the datetime object, convert it to a unix timestamp using time.mktime.
import time
import datetime as dt
from time import mktime
from datetime import datetime
now1 = dt.datetime.now()
current_month= now1.month
current_year= now1.year
month_start_date= dt.datetime.today().strftime("%Y/%m/01")
month_end_date= "30"
final_month_end_date= dt.datetime.today().strftime("%Y/%m/"+month_end_date)
# Use datetime.strptime to convert from string to datetime
month_start = datetime.strptime(month_start_date, "%Y/%m/%d")
month_end = datetime.strptime(final_month_end_date, "%Y/%m/%d")
# Use time.mktime to convert datetime to timestamp
timestamp_start = time.mktime(month_start.timetuple())
timestamp_end = time.mktime(month_end.timetuple())
# Let's print the time stamps
print "Start timestamp: {0}".format(timestamp_start)
print "End timestamp: {0}".format(timestamp_end)

Python: convert 'days since 1990' to datetime object

I have a time series that I have pulled from a netCDF file and I'm trying to convert them to a datetime format. The format of the time series is in 'days since 1990-01-01 00:00:00 +10' (+10 being GMT: +10)
time = nc_data.variables['time'][:]
time_idx = 0 # first timestamp
print time[time_idx]
9465.0
My desired output is a datetime object like so (also GMT +10):
"2015-12-01 00:00:00"
I have tried converting this using the time module without much success although I believe I may be using wrong (I'm still a novice in python and programming).
import time
time_datetime = time.strftime('%Y-%m-%d %H:%M:%S', time.gmtime(time[time_idx]*24*60*60))
Any advice appreciated,
Cheers!
The datetime module's timedelta is probably what you're looking for.
For example:
from datetime import date, timedelta
days = 9465 # This may work for floats in general, but using integers
# is more precise (e.g. days = int(9465.0))
start = date(1990,1,1) # This is the "days since" part
delta = timedelta(days) # Create a time delta object from the number of days
offset = start + delta # Add the specified number of days to 1990
print(offset) # >>> 2015-12-01
print(type(offset)) # >>> <class 'datetime.date'>
You can then use and/or manipulate the offset object, or convert it to a string representation however you see fit.
You can use the same format as for this date object as you do for your time_datetime:
print(offset.strftime('%Y-%m-%d %H:%M:%S'))
Output:
2015-12-01 00:00:00
Instead of using a date object, you could use a datetime object instead if, for example, you were later going to add hours/minutes/seconds/timezone offsets to it.
The code would stay the same as above with the exception of two lines:
# Here, you're importing datetime instead of date
from datetime import datetime, timedelta
# Here, you're creating a datetime object instead of a date object
start = datetime(1990,1,1) # This is the "days since" part
Note: Although you don't state it, but the other answer suggests you might be looking for timezone aware datetimes. If that's the case, dateutil is the way to go in Python 2 as the other answer suggests. In Python 3, you'd want to use the datetime module's tzinfo.
netCDF num2date is the correct function to use here:
import netCDF4
ncfile = netCDF4.Dataset('./foo.nc', 'r')
time = ncfile.variables['time'] # do not cast to numpy array yet
time_convert = netCDF4.num2date(time[:], time.units, time.calendar)
This will convert number of days since 1900-01-01 (i.e. the units of time) to python datetime objects. If time does not have a calendar attribute, you'll need to specify the calendar, or use the default of standard.
We can do this in a couple steps. First, we are going to use the dateutil library to handle our work. It will make some of this easier.
The first step is to get a datetime object from your string (1990-01-01 00:00:00 +10). We'll do that with the following code:
from datetime import datetime
from dateutil.relativedelta import relativedelta
import dateutil.parser
days_since = '1990-01-01 00:00:00 +10'
days_since_dt = dateutil.parser.parse(days_since)
Now, our days_since_dt will look like this:
datetime.datetime(1990, 1, 1, 0, 0, tzinfo=tzoffset(None, 36000))
We'll use that in our next step, of determining the new date. We'll use relativedelta in dateutils to handle this math.
new_date = days_since_dt + relativedelta(days=9465.0)
This will result in your value in new_date having a value of:
datetime.datetime(2015, 12, 1, 0, 0, tzinfo=tzoffset(None, 36000))
This method ensures that the answer you receive continues to be in GMT+10.

calculating the next day from a "YYYYMMDD" formatted string

How can I calculate the next day from a string like 20110531 in the same YYYYMMDD format? In this particular case, I like to have 20110601 as the result. Calculating "tomorrow" or next day in static way is not that tough, like this:
>>> from datetime import date, timedelta
>>> (date.today() + timedelta(1)).strftime('%Y%m%d')
'20110512'
>>>
>>> (date(2011,05,31) + timedelta(1)).strftime('%Y%m%d')
'20110601'
But how can I use a string like dt = "20110531" to get the same result as above?
Here is an example of how to do it:
import time
from datetime import date, timedelta
t=time.strptime('20110531','%Y%m%d')
newdate=date(t.tm_year,t.tm_mon,t.tm_mday)+timedelta(1)
print newdate.strftime('%Y%m%d')
>>> from datetime import datetime
>>> print datetime.strptime('20110531', '%Y%m%d')
2011-05-31 00:00:00
And then do math on that date object as you show in your question.
The datetime library docs.
You are most of the way there! along with the strftime function which converts a date to a formatted string, there is also a strptime function which converts back the other way.
To solve your problem you can just replace date.today() with strptime(yourDateString, '%Y%m%d').
ED: and of course you will also have to add strptime to the end of your from datetime import line.

Categories