Get the time from a string datetime that have special characters - python

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.

Related

Convert custom string date to date

Is there a way to convert a string date that is stored in some non-traditional custom manner into a date using datetime (or something equivalent)? The dates I am dealing with are S3 partitions that look like this:
year=2023/month=2/dayofmonth=3
I can accomplish this with several replaces but im hoping to find a clean single operation to do this.
You might provide datetime.datetime.strptime with format string holding text, in this case
import datetime
dt = datetime.datetime.strptime("year=2023/month=2/dayofmonth=3","year=%Y/month=%m/dayofmonth=%d")
d = dt.date()
print(d) # 2023-02-03
you can do that converting your string into a date object using "datetime" combined with strptime() method.
The strtime() takes two arguments, the first is the string to be parsed, and the second a string with the format.
Here's an example:
from datetime import datetime
# your string
date_string = "year=2023/month=2/dayofmonth=3"
# parse the string into a datetime object
date = datetime.strptime(date_string, "year=%Y/month=%m/dayofmonth=%d")
# print the datetime object
print(date)

Python: ValueError raised when parsing a datetime string

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

Which method to convert strings in a UTC format into day-month-year string?

I would like to convert two lists of strings into lists with one same time format.
Here are our two lists:
# first list: strings with UTC format
firstlist = ['2013-08-16T07:35:01Z','2012-11-17T17:07:49Z','2012-11-09T23:24:13Z']
# second list: strings with day-month-year format
secondlist = ['04-06-2016','31-10-2018','12-04-2019']
I would like to convert these two lists and get the same format year-month-day for each item:
['2013-08-16','2012-11-17','2012-11-09'] # expected for the first list
['2016-06-04','2018-10-31','2019-04-12'] # expected for the second list
I tried with just one item per list:
import time
time.strptime("2013-08-16T07:35:01Z", "%d %m %y")
time.strptime("04-06-2016", "%d %m %y")
But I get an error:
ValueError: time data '2013-08-16T07:35:01Z' does not match format '%d %m %y'
I found these two documentations: time and datetime.
But I am still really confused. There is probably something wrong with my method, but I struggle to find the right one for this case.
strptime returns a struct_time object, given a string to parse. You need to specify the date/time format of the actual input string:
import time
# string to time struct
a = time.strptime("2013-08-16T07:35:01Z", "%Y-%m-%dT%H:%M:%SZ")
b = time.strptime("04-06-2016", "%d-%m-%Y")
Then, use strftime to format the struct_time object into a string:
# time struct to formatted string
a_formatted = time.strftime('%Y-%m-%d', a)
b_formatted = time.strftime('%Y-%m-%d', b)
print(a_formatted,b_formatted)
Output:
2013-08-16 2016-06-04
This does it
import dateutil.parser
firstlist = list (map (lambda x: str (dateutil.parser.parse (x).date()), firstlist))
secondlist = list (map (lambda x: str (dateutil.parser.parse (x).date()), secondlist))
Use dateutil.parser.parse to convert to datetime.
Source: here
You can use dateutil parser to parse almost any time format.
import datetime
from dateutil.parser import parse
firstlist = ['2013-08-16T07:35:01Z','2012-11-17T17:07:49Z','2012-11-09T23:24:13Z']
secondlist = ['04-06-2016','31-10-2018','12-04-2019']
new_firstlist = [datetime.datetime.strftime(parse(dt), "%Y-%m-%d") for dt in firstlist]
new_secondlist = [datetime.datetime.strftime(parse(dt), "%Y-%m-%d") for dt in secondlist]
print(new_firstlist)
print(new_secondlist)

Checking that a string of the date and time is for the most recent hour

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

strip date with -07:00 timezone format python

I have a variable 'd' that contains dates in this format:
2015-08-03T09:00:00-07:00
2015-08-03T10:00:00-07:00
2015-08-03T11:00:00-07:00
2015-08-03T12:00:00-07:00
2015-08-03T13:00:00-07:00
2015-08-03T14:00:00-07:00
etc.
I need to strip these dates, but I'm having trouble because of the timezone. If I use d = dt.datetime.strptime(d[:19],'%Y-%m-%dT%H:%M:%S'), only the first 19 characters will appear and the rest of the dates are ignored. If I try d = dt.datetime.strptime(d[:-6],'%Y-%m-%dT%H:%M:%S, Python doesn't chop off the timezone and I still get the error ValueError: unconverted data remains: -07:00. I don't think I can use the dateutil parser because I've only seen it be used for one date instead of a whole list like I have. What can I do? Thanks!
Since you have a list just iterate over and use dateutil.parser:
d = ["2015-08-03T09:00:00-07:00","2015-08-03T10:00:00-07:00","2015-08-03T11:00:00-07:00","2015-08-03T12:00:00-07:00",
"2015-08-03T13:00:00-07:00","2015-08-03T14:00:00-07:00"]
from dateutil import parser
for dte in d:
print(parser.parse(dte))
If for some reason you actually want to ignore the timezone you can use rsplit with datetime.strptime:
from datetime import datetime
for dte in d:
print(datetime.strptime(dte.rsplit("-",1)[0],"%Y-%m-%dT%H:%M:%S"))
If you had a single string delimited by commas then just use d.split(",")
You can use strftime to format the string in any format you want if you actually want a string:
for dte in d:
print(datetime.strptime(dte.rsplit("-",1)[0],"%Y-%m-%dT%H:%M:%S").strftime("%Y-%m-%d %H:%M:%S"))

Categories