How to check the date is empty using python?
Change this line
if (startdate and enddate) == "":
to
if startdate == "" and enddate == "":
Another way:
if not startdate and not enddate: # PEP 8 recommended
Check if datetime column is empty
Here is better/faster use numpy.where
with Series.isna
:
df['term'] = np.where(df['date_pogash_posle_prodl'].isna(),
df['date_pogash'] - df['date_dogovor'],
df['date_dogovor'] - df['date_dogovor'])
Your function should be changed with pandas.isna
:
def term(date_contract , date_paymnt, date_paymnt_aftr_prlngtn):
if pd.isna(date_paymnt_aftr_prlngtn):
return date_paymnt - date_contract
else:
return date_paymnt_aftr_prlngtn - date_contract
How to check when a date is not filled in python?
You can use isnull
>>> df
Year Week_No Value
0 2015-01-01 52 3
1 2016-01-01 2 7
2 NaT 51 5
3 2016-01-01 1 6
4 2015-01-01 50 4
>>>
>>>
>>> df.Year.isnull()
0 False
1 False
2 True
3 False
4 False
Name: Year, dtype: bool
Python validate date using pydantic to accept empty string
Your first error is normal. Indeed, you ask for either a date, or None
, but you pass a string, certainly, empty but a string nevertheless, so, you do not correspond to the scheme.
The solution I see to accept a date or an empty string only, would be to write your schema with an Union, and write your own validator as follows:
def date_validator(date):
if not isinstance(date, datetime) and len(date) > 0:
raise ValueError(
"date is not an empty string and not a valid date")
return date
class EmployeeInput(BaseModel):
last_name: str = ''
first_name: str = ''
date: Union[datetime, str] = get_date_now()
_date_validator = validator(
'date', allow_reuse=True)(date_validator)
DateTime variable is empty
You can use pd.Nat
like if df.iloc[i]['endedAt'] is pd.NaT:
:
import pandas as pd
dt = pd.to_datetime([
None,
pd.Timestamp("2018-11-20 01:10:43"),
pd.Timestamp("2018-11-19 20:21:57"),
pd.Timestamp("2018-11-19 20:06:23"),
pd.Timestamp("2018-11-19 04:05:36"),
])
df = pd.DataFrame({"endedAt": dt})
print(df)
for i in range(len(df)):
if df.iloc[i]['endedAt'] is pd.NaT:
print("\nNaT row index:", i)
Out:
endedAt
0 NaT
1 2018-11-20 01:10:43
2 2018-11-19 20:21:57
3 2018-11-19 20:06:23
4 2018-11-19 04:05:36
NaT row index: 0
Check if a variable is not empty
Try the following selection statement:
if (picked < prev_final) and isinstance(new_date, pd.datetime) and (new_date is not None)
Null Value in Date field of Data Frame, how to skip it to format as date
You can try apply
:
import datetime
import numpy as np
df=pd.DataFrame({'dt':[1564025326921, 1564025327921, None, 1564025328921]})
df['dt'] =df['dt']/1000.0
df['dt']= df['dt'].apply(lambda t: None if np.isnan(t) else datetime.datetime.fromtimestamp(t).strftime('%d/%m/%Y'))
df.head(10)
This will output:
dt
0 24/07/2019
1 24/07/2019
2 None
3 24/07/2019
Issue with str_to_date() function with Empty field
Rather than processing the dates in the query, you could pre-process them in your python code. For example:
from datetime import datetime
dstr = ''
try:
dateannounced = datetime.strptime(dstr, '%d/%m/%Y').strftime('%Y-%m-%d')
except ValueError:
dateannounced = None
Then your query simply becomes
cursor.execute("INSERT INTO covid_testtable (pid, age, state, city, notes, backnotes, type, nationality, status, announced, changed) " +
"VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)",
(pid, age, item["detectedstate"], item["detectedcity"],
item["notes"], item["backupnotes"], item["typeoftransmission"],
item["nationality"], item["currentstatus"], dateannounced,
statuschanged));
Related Topics
What Is the Most Pythonic Way to Check If Multiple Variables Are Not None
Read Multiple Images on a Folder in Opencv (Python)
How to Read a Column Without Header from CSV and Save the Output in a Txt File Using Python
How to Get the Neighboring Elements in a Numpy Array With Taking Boundaries into Account
How to Iterate Over a Timespan After Days, Hours, Weeks and Months
How to Make a Smiley Face in Turtle
Blender - How to Add a Color to an Object
How to Send Smtp Email for Office365 With Python Using Tls/Ssl
Python - How to Separate Paragraphs from Text
How to Change Border Color in Tkinter Widget
Stored Procedures With Sqlalchemy
In Python, How to Check If a Date Is Valid
Efficient Date Range Overlap Calculation
How to Convert an Integer to Time