The following ValueError is being raised while running the following code. The date is passed as a string from an another component, where I need to strip out the time.
ValueError: time data '2022-03-24T14:02:24.6413975' does not match format '%Y-%m-%d %H:%M:%S,%f'
The code:
from datetime import datetime
date='2022-03-24T14:02:24.6413975'
time = datetime.strptime(date, "%Y-%m-%d %H:%M:%S,%f")
if time > '09:30' :
print("do some thing")
The primary issue you're facing is the datetime format, as explained by the error message.
The .%f formatter can only accept six decimal places.
The T is missing from the format string.
There is a comma before the %f formatter, where there should be a full stop.
Therefore, this is the formatting string you need:
'%Y-%m-%dT%H:%M:%S.%f'
Additionally, time can be parsed from a datetime object simply by calling the .time() function as follows. String parsing should not be used, if at all possible.
time = dt.datetime.strptime(date, "%Y-%m-%dT%H:%M:%S.%f").time()
Next, the if statement should compare datetime object to datetime object, as:
if time > dt.time(9,30):
...
Therefore, the complete solution is as follows:
import datetime as dt
# Fractional seconds reduced to 6 decimal places.
date = '2022-03-24T14:02:24.641397'
# Use the .time() function to extract the time.
time = dt.datetime.strptime(date, '%Y-%m-%dT%H:%M:%S.%f').time()
# Compare datetime object to datetime object.
if time > dt.time(9,30):
print('Do some stuff ...')
This should work:
import datetime
date='2022-03-24T14:02:24.6413975'
time = date.split('T')[1].split(':')
time = datetime.time(int(time[0]), int(time[1]), int(time[2].split('.')[0]), int(time[2].split('.')[1][:6]))
if time > datetime.time(9, 30) :
print("do some thing")
Output:
do some thing
This just takes date, splits it T, splits the second part of the resulting string at every :, and passes all of them to datetime.time. The last two arguments to datetime.time have to be split a the decimal to get the microseconds, and the last one has to be shortened because of the limit on how long datetime allows microseconds to be.
Hope this may help:
def stripTime():
date='2022-03-24T14:02:24.6413975'
date=date.split('T')
print(date[1])
stripTime()
Output:
14:02:24.6413975
Related
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.
I'm trying to get current date so I can pass it to the DATE field in SQL. I'm using datetime.datetime, below is my code:
from datetime import datetime
dt = datetime.strptime(datetime.today().date(), "%m/%d/%Y").date()
However, i'm getting this error:
TypeError: strptime() argument 1 must be str, not datetime.datetime
How can I fix the issue above? I'm still confused about datetime and datetime.datetime, and i want to keep using from datetime import datetime not import datetime.
How can I fix the issue above? thank you
If you see closely, the result of following statement,
>>> datetime.today().date()
datetime.date(2019, 9, 30)
>>> str(datetime.today().date())
'2019-09-30'
You'll notice that the datetime returned is - seperated and you'll have to convert it explicitly to a string value. Hence, for the above statement to work, change it to :
dt = datetime.strptime(str(datetime.today().date()), "%Y-%M-%d").date()
Then change it to whatever format you desire for using strftime (in your case >>> "%d/%m/%Y")
>>> dt.strftime("%d/%m/%Y")
'30/01/2019'
Just use datetime.strftime:
from datetime import datetime
dt = datetime.today().strftime("%m/%d/%Y")
print(dt)
Prints:
'09/30/2019'
strptime takes a string and makes a datetime object. Whereas strftime does exactly the opposite, taking a datetime object and returning a string.
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.
I am trying to get the time from this string 2017-11-07 16:56:34.787-08 while using the code below:
from datetime import datetime
my_string = '2017-11-07 16:56:34.787-08'
dt = datetime.strptime(my_string, "%Y-%m-%d %H:%M:%S.%f")
However my_string is slightly unique as it is appended with -08 that is appended behind, and at times it can be in 3-digits form eg. -123
Instead of doing a roundabout method, using split('-') then remove the last element, is there a better method that I can get the time directly?
I would suggest using rsplit(), which will avoid having to join() the split() result (since the date contains other dashes).
from datetime import datetime
my_string = '2017-11-07 16:56:34.787-08'
date_string, _ = my_string.rsplit('-', 1)
dt = datetime.strptime(date_string, "%Y-%m-%d %H:%M:%S.%f")
print(dt)
# 2017-11-07 16:56:34.787000
There is no way to use strptime() with characters to ignore, date string and format must match:
If string [...] has excess data after parsing, ValueError is raised.
In my script I have a string containing the date and the time in the following format:
>>>mystring.text
'05/08/201714:00:00'
What is the best way to compare the string with the output from the datetime.now() method to check if the string contains the most recent hour? Basically, what is the 'operation' I need to do in order to make the following conditional statement:
time = operation(mystring.text)
if time == datetime.now().replace(microsecond=0,second=0,minute=0):
pass
It would be probably make sense to do the comparison in datetime format as follows:
from datetime import datetime
mystring = "05/08/201714:00:00"
dt_mystring = datetime.strptime(mystring, "%d/%m/%Y%H:%M:%S")
print dt_mystring.replace(microsecond=0,second=0,minute=0) == datetime.now().replace(microsecond=0,second=0,minute=0)eplace(microsecond=0,second=0,minute=0)
strptime() is used to convert your string into a datetime object.
The formatting characters are: strptime() Behavior