Date String in Datetime Format Python - python

Here is my error I do not manage to solve
ValueError: time data '1/31/2021 22:59' does not match format '%d/%m/%Y %H:%M:%S'
Here is my code
90% of the time my String date I need to convert goes in my try part and It works, I have a problem with my second part.
def StringToDateTime(DateString):
from datetime import datetime
try:
return datetime.strptime(DateString, '%Y-%m-%d %H:%M:%S')
except:
DateString = str(DateString)+':00'
return datetime.strptime(DateString, '%d/%m/%Y %H:%M:%S')

The error you're seeing is due to the str not having a seconds value -- the %S of the datetime format string.
Change the format string so it doesn't have the seconds placeholder, and it should work as expected:
try:
# Remove the %S from the format string here
return datetime.strptime(DateString, '%Y-%m-%d %H:%M')
except:
DateString = str(DateString)+':00'
return datetime.strptime(DateString, '%d/%m/%Y %H:%M:%S')
Or, if you want to alter the DateString as you do in your except clause:
# Add the seconds to the date string
DateString = f"{DateString}:00"
try:
return datetime.strptime(DateString, '%Y-%m-%d %H:%M:%S')
except:
return datetime.strptime(DateString, '%d/%m/%Y %H:%M:%S')

Related

How do I convert a string to a datetime without many nested try...excepts?

I'm trying to check user input of a date/time in several allowable formats. (I know about the dateutil library. It's not what I'm looking for in this case.)
If some user input was accepted, the function must return a datetime object.
If ALL "try...except" fail — the function must return NONE. But I have 30-50 different date/time formats that I need to check.
I'm confused by the huge indentation in my code! How do I organize this format checking in a good style with GOOD performance?
# Test format check program
import datetime
def datetime_format_check(str):
try:
dt = datetime.datetime.strptime(str, "%y-%m-%d %H:%M")
return dt
except:
try:
dt = datetime.datetime.strptime(str, "%Y-%m-%d %H:%M")
return dt
except:
try:
dt = datetime.datetime.strptime(str, "%y-%m-%d")
return dt
except:
try:
dt = datetime.datetime.strptime(str, "%Y-%m-%d")
return dt
except:
try:
dt = datetime.datetime.strptime(str, "%H:%M")
return dt
except:
try:
# . . .
# many many try...except blocks )))
# . . .
return None # last except far far away from a screen border. ))))
while True:
str = input("Input date: ")
print("Result: ", datetime_format_check(str))
Repetitive code? Well, that just begs to be replaced with a loop.
Put all of the formats in a list and iterate over it, checking each format:
def datetime_format_check(s):
formats = ["%y-%m-%d %H:%M", "%Y-%m-%d %H:%M", "%y-%m-%d"] # etc
for format in formats:
try:
dt = datetime.datetime.strptime(s, format)
return dt
except ValueError:
pass
return None
Some minor corrections I made to your code:
Don't name your argument str; it shadows the builtin.
Don't use a bare except:, always catch the specific exception.

Convert hour string containing pm to datetime

I want to convert a string that contains PM notation to a datetime type. Thanks!
datetime.strptime('8/18/2020 11:08:54 PM', '%m/%d%Y %I:%M:%S %p' )
I am getting this error
ValueError: time data '8/18/2020 11:08:54 PM' does not match format '%m/%d%Y %I:%M:%S %p'
You can use this code. It's very simple.
r = datetime.strptime('8/18/2020 11:08:54 PM', '%m/%d/%Y %I:%M:%S %p')
Or
import dateparser
r = dateparser.parse('8/18/2020 11:08:54 PM')
print(r)
Here is an answer using the builtin datetime module:
from datetime import datetime
date_str = '8/18/2020 11:08:54 PM'
fmt = '%m/%d/%Y %I:%M:%S %p'
parsed_date = datetime.strptime(date_str, fmt)

What is a solution to this error TypeError: strptime() argument 1 must be str, not datetime.date

can please anyone helps me with my code?
this is the error that I got
I just don't get it on how did I get this error:
CurrentDate = datetime.datetime.strptime(CurrentDate, "%Y-%m-%d %H:%M")
TypeError: strptime() argument 1 must be str, not datetime.date
Full code:
import datetime
CurrentDate = datetime.datetime.now().date()
print(CurrentDate)
Run4Start = str(CurrentDate) + " 16:00"
Run4End = str(CurrentDate) + " 20:00"
Run4Start = datetime.datetime.strptime(Run4Start, "%Y-%m-%d %H:%M")
Run4End = datetime.datetime.strptime(Run4End, "%Y-%m-%d %H:%M")
print("RUN4 :", CurrentDate )
print(Run4Start, Run4End)
CurrentDate = datetime.datetime.strptime(CurrentDate, "%Y-%m-%d %H:%M")
print(CurrentDate)
if CurrentDate >= Run4Start and CurrentDate <= Run4End:
print("Hit")
else:
print("Miss!")
In:
CurrentDate = datetime.datetime.strptime(CurrentDate, "%Y-%m-%d %H:%M")
CurrentDate is already a datetime.date object, created above:
CurrentDate = datetime.datetime.now().date()
and never changed to anything else. So you don't need to parse it, it's already "parsed". Just remove the line attempting to parse it.
That said, it's just a date, and you're comparing it to datetimes on a specific day; whether or not it works, it won't do what you're probably trying to do (determine if the current time is between 1600 and 2000). You don't need string parsing to do that at all; your entire block of code testing for a hit vs. miss could simplify to:
if datetime.time(16) <= datetime.datetime.now().time() <= datetime.time(20):
print("Hit")
else:
print("Miss!")
since you only care about the time component, not the date component at all.

Convert datetime to local time

I'm doing a parse from string ISO8601 to a datetime and it's working. Now I want to return datetime on localtime but my code is returning same timestamp from input:
def format_string_to_timestamp(dt, defaultTimezone='America/Sao_Paulo'):
origin_dt = datetime.strptime(dt, '%Y-%m-%dT%H:%M:%S.%f')
tz_local = pytz.timezone (defaultTimezone)
dt_local = origin_dt.astimezone(tz_local).replace(tzinfo=None)
print(dt)
print(dt_local)
print(origin_dt)
return dt_local.strftime('%Y-%m-%d %H:%M:%S')
# example input: 2019-02-25T17:58:53.753
What is missing to return dt_local as America/Sao_Paulo timezone?

Python CSV Finding average time taken

I am trying to find the average time taken. The value 'x' will allow me to get the time taken for every row there is, but how am I able to find the average time taken for all the rows. I will think it is something like x divided by count, but I am not able to find a solution to this... any pros out there can help me??
import datetime,time,csv
from itertools import islice
from Tkinter import Tk #python GUI programming
from tkFileDialog import askopenfilename
from collections import Counter
from datetime import datetime
import pandas
Tk().withdraw()
category_list=[]
description_list=[]
reported_date=[]
acknowledged_date=[]
count = 0
# hard code all possible date formats
date_formats = ['%m/%d/%Y %H:%M', '%-d-%b-%y', '%d/%m/%Y %h:%M %p', '%d/%m/%Y %H:%M', '%A, %d %B %Y %H:%M','%A, %d %B %Y %H:%M','%A %d %B %Y %H%M',"%d/%m/%Y %H:%M %p"," %d/%m/%Y %H:%M %p", '%d-%b-%y' ,
'%d.%m.%Y', '%d %b %Y %H%M hrs', '%d %b %Y %H%M', '%d-%m-%y', '%d-%b-%y', '%b-%d-%y', '%d-%a-%y','%e-%a-%y','%b %d %Y %H%M hrs','%d/%b/%Y %m:%M %p','%A, %e %B %Y %H:%M',' %d/%m/%Y %h:%M','%d-%b-%y','%m/%d/%Y %H:%M:%S %p']
#file = askopenfilename() #ask user which file to open
#f = open(file,'r')
with open('Feedback and Complaints_Sample Dataset.csv', 'rb') as f:
reader = csv.reader(f)
header = next(reader) #read 2nd line onwards
data= [] #make a list called data
for row in reader: #assign data in every column and name them respectively
for format in date_formats:
try:
reported_on = datetime.strptime(row[0], format) #try and get the dates
acknowledged_on = datetime.strptime(row[12], format) #try and get the dates
x= acknowledged_on-reported_on #time taken to acknowledge
#acknowledged_date.append(acknowledged_on)
#reported_date.append(reported_on)
count += 1
break # if correct format, dont test any other formats
except ValueError:
pass # if incorrect format, try other formats`enter code here`
Subtracting two datetime objects creates a timedelta object. You need to keep a total time, so create a timedelta object, and for each x add it to your total.
At the end, you can then divide your total_time by your count:
import csv
from itertools import islice
from datetime import datetime, timedelta
count = 0
total_time = timedelta()
# hard code all possible date formats
date_formats = ['%m/%d/%Y %H:%M', '%-d-%b-%y', '%d/%m/%Y %h:%M %p', '%d/%m/%Y %H:%M', '%A, %d %B %Y %H:%M','%A, %d %B %Y %H:%M','%A %d %B %Y %H%M',"%d/%m/%Y %H:%M %p"," %d/%m/%Y %H:%M %p", '%d-%b-%y' ,
'%d.%m.%Y', '%d %b %Y %H%M hrs', '%d %b %Y %H%M', '%d-%m-%y', '%d-%b-%y', '%b-%d-%y', '%d-%a-%y','%e-%a-%y','%b %d %Y %H%M hrs','%d/%b/%Y %m:%M %p','%A, %e %B %Y %H:%M',' %d/%m/%Y %h:%M','%d-%b-%y','%m/%d/%Y %H:%M:%S %p']
with open('Feedback and Complaints_Sample Dataset.csv', 'rb') as f:
reader = csv.reader(f)
header = next(reader) #read 2nd line onwards
for row in reader:
for format in date_formats:
try:
reported_on = datetime.strptime(row[0], format) #try and get the dates
acknowledged_on = datetime.strptime(row[12], format) #try and get the dates
x = acknowledged_on - reported_on #time taken to acknowledge
total_time += x
count += 1
break # if correct format, don't test any other formats
except ValueError:
pass # if incorrect format, try other formats`enter code here`
print "Total time taken:", total_time
print "Average time taken:", total_time / count
Note: your logic for the date_formats implies that both dates in a single row will always share the same date format.

Categories

Resources