Datetime object- Extract the values - pyqt5

Using QT designer i have a date and time object like below
How can i extract the time and date entered in this one by one, i.e
Hour = 03 (since it is AM)
Minutes= 00
Seconds = 00
Date = 01
month= 01
year=2000

You can use strptime() to convert strings to datetime objects.
from datetime import datetime
entry_date = "01/01/2000" # string from the first widget
entry_time = "3:00 AM" # string from the second widget
entry = datetime.strptime(entry_date + entry_time, "%d/%m/%Y%I:%M %p")
Then you access individual time and date components like this:
print(entry.year, entry.month, entry.day)
print(entry.hour, entry.minute, entry.second)
Output:
2000 1 1
3 0 0
If you need zero-padded values, use strftime() to convert datetime objects back to strings. For example:
print("Month =", entry.strftime("%m"))
print("Date =", entry.strftime("%d"))
Output:
Month = 01
Date = 01
See this table for all possible formatting tokens.
UPDATE:
(I assume you are using the widgets QDateEdit and QTimeEdit)
Suppose your widgets are called entryDate and entryTime. Then you would get the individual strings like this:
self.entryDate.date().toString("yyyy")
self.entryDate.date().toString("MM")
self.entryDate.date().toString("dd")
self.entryTime.time().toString("hh")
self.entryTime.time().toString("mm")
self.entryTime.time().toString("ss")
Here are the values to play with. (tested in PySide2 but this should work in PyQt5)

Related

Getting the last day of month given a specific datetime variable in SAS EG

How do I get the last day of the month given a datetime variable like:
29DEC2022:00:00:00.000000
I want to convert the variable to:
31DEC2023:00:00:00.000000
And get a similar result if I input the datetime variable:
15DEC2022:00:00:00.000000
I hope you can help me in the right direction
It is unclear if you want a date or datatime result. This gives datetime.
37 data _null_;
38 x = '29DEC2022:00:00:00.000000'dt;
39 l = intnx('DTMONTH',x,0,'E');
40 put (x l)(=datetime.);
41 run;
x=29DEC22:00:00:00 l=31DEC22:23:59:59

How to compare two datetime value instead of string using VB.Net

How to compare two datetime values?
For example as per below condition, I have FDatetimes value is string coming (i.e 2021-06-21 17:00:30Z) from database and SDatetimes value should be Datetime.UtcNow. So my requirement is both left and right side always compare with datetime instead of string.
Also I have tried to use Convert.ToDateTime(FDatetimes). But there is one issue here. Whenever I have used the above function, That time the time is getting changed to 2021-06-21 10:00:30Z. My main aim is to compare both field value as DateTime instead of String. Please help in VB.Net
If FDatetimes < SDatetimes Then
'My logic
End If
So to resolve DST issues I did this (which I ran at 9:20AM local, 14:20 UTC on 23 Jun 2021)
Dim SDatetimes As DateTime = DateTime.UtcNow
Dim FDatetimes As String = "2021-06-23 15:20:30Z"
Dim FDT As DateTime = DateTime.ParseExact(FDatetimes,
"yyyy-MM-dd HH:mm:ssZ",
Globalization.CultureInfo.InvariantCulture,
Globalization.DateTimeStyles.AdjustToUniversal Or
Globalization.DateTimeStyles.AssumeUniversal)
Debug.WriteLine(SDatetimes.ToString)
Debug.WriteLine(FDT.ToString)
If FDT < SDatetimes Then
'My logic
Stop
End If

Calculate number of days left from nearest date in Pandas

I have a list like this:
dates = ["2020-05-08","2019-02-22", "2014-08-16"...........]
And a DF like this:
date .....
2020-12-19 .....
2015-06-01 .....
2018-03-06 ....
......
I want to create another column named "daysLeft", which count, the days from the nearest date.
For example.
If today is 24th Dec, then "1" day is left for chrismas. But if today is 26th Dec, "-1" day is left for Christmas. (Subtract date with nearest date)
I am not sure in this answers your question, but this might be a step in the right direction:
#This Function Converts String to DateTime Object for Date Manipulation
from datetime import datetime
def make_date(any_value):
return datetime.strptime(any_value, '%Y-%m-%d')
#We apply thr Function to the list
dates = ["2020-05-08","2019-02-22", "2014-08-16"]
dt_obj = list(map(make_date, dates))
#We apply the function to the DataFrame
date_df_list=["2020-12-19", "2015-06-01", "2018-03-06" ]
import pandas
date_df=pandas.DataFrame(date_df_list, columns=["date"])
date_df['date'] = date_df['date'].astype(str) #Each object needs to be converted to String for Function
date_df_yyyymmdd = pandas.DataFrame(columns=['date']) #Initialise Empty DataFrame
date_df_yyyymmdd['date'] = date_df['date'].apply(make_date)
#In this example we Find Difference in Dates for the first date of list
#Similarly we can find for all the other dates in the list
date_df['daysLeft'] = date_df_yyyymmdd['date'].apply(lambda x: (x-dt_obj[1]).days)
print(date_df)

How do I convert a non zero padded day string to a useful date in pandas

I'm trying to import a date string with non-zero padded day, zero padded month, and year without century to create a datetime e.g. (11219 to 01/12/19). However, pandas cannot distinguish between the day and the month (e.g. 11219 could be 11th February, 2019 or 1st December, 2019).
I've tried using 'dayfirst' and the '#' in the day e.g. %#d, but nothing works. Code below, any advise?
Code:
df_import['newDate'] = pd.to_datetime(df_import['Date'], format='%d/%m/%Y', dayfirst = True)
Error:
time data '11219' does not match format '%d/%m/%Y' (match)
Since only the day is not zero-padded, the dates are unambiguous. They can simply be parsed by Pandas if we add the pad:
pd.to_datetime(df_import['Date'].str.zfill(6), format='%d%m%y')
use zfill()
A custom function can also be used if you want to handle more cases.
def getDate(str):
return #logic to parse
df_import['newDate'] = df_import['Date'].apply(getDate)

datetime - How to strip just date and validate the date

from selenium import webdriver
import time
from datetime import datetime
driver = webdriver.Chrome(executable_path ="C:/ChromeDriver/chromedriver.exe")
driver.maximize_window()
driver.get("http://www.timestampconvert.com")
driver.implicitly_wait(2)
time.sleep(2)
date_displayed = driver.find_element_by_xpath('/html/body/div[4]/div[2]/form/div/div[3]/div/span[5]')
print('Date displayed on page:', date_displayed.text)
try:
datetime.strptime(date_displayed.text, '%d-%m-%Y %H:%M:%S')
print('The date format {} is valid.'.format(date_displayed.text))
except ValueError:
print('The date {} is invalid'.format(date_displayed.text))
The above code executes fine BUT It doesn't do what I am expecting
1. I just want the date to be displayed and strip time, but it displays both date and time?
2. How do i validate the date and month?
For example
If date is displayed as 24/05/2020 - It should pass because expected date format is DD-MM-YYYY
If date is displayed as 06/16/2020 - It should Fail because expected date format is DD-MM-YYYY but actual format displayed is MM/DD/YYYY
--
I have a requirements to test specific date formats on my applications and i want to specify
first digit is always 'DD' and it range from 1 to 31
second digit is always 'MM' and it range from 1 to 12
it should validate and should pass / fail the test accordingly.
Any suggestions please?
why not
try:
mydate=date_display.test.split(" ")[0]
datetime.strptime(mydate, '%d-%m-%Y')
print('The date format {} is valid.'.format(mydate))
except ValueError:
print('The date {} is invalid'.format(mydate))