Python How to check the string is a UTC timestamp? - python-3.x

I need to check if the string of timestamp belongs to 'UTC' timestamp
i have below code
def time_stamp():
utc = timezone('UTC')
time_stamp = datetime.now(utc)
utc_time_stmap = time_stamp.strftime("%Y-%m-%dT%H:%M:%S.%f")
return utc_time_stmap
the above function return the utc time in a string format
print(type(time_stamp()))
<class 'str'>
print(time_stamp())
'2021-02-10 15:49:57.906168'
The 'time_stamp()' return the timestamp in 'string type'.
#Expected:
i need to check the return value falls within a tight date UTC date range?
Appreciated for the the help?
Thanks

Here you get some code where you may find your answer.
import re
from datetime import datetime
DATETIME_ISO8601 = re.compile(
r'^([0-9]{4})' r'-' r'([0-9]{1,2})' r'-' r'([0-9]{1,2})' # date
r'([T\s][0-9]{1,2}:[0-9]{1,2}:?[0-9]{1,2}(\.[0-9]{1,6})?)?' # time
r'((\+[0-9]{2}:[0-9]{2})| UTC| utc)?' # zone
)
def datetime_iso(string):
""" verify rule
Mandatory is: 'yyyy-(m)m-(d)dT(h)h:(m)m'
"""
string = string.strip()
return bool(re.fullmatch(DATETIME_ISO8601, string))
def utc_timezone(datetime_string):
datetime_string = datetime_string.strip()
return datetime_string.endswith("00:00") or datetime_string.upper().endswith("UTC")
check_this = ["2020-1-1 22:11", "2020-1-1 22:11:34 00:00", "2020-1-1 22:11:34+00:00", "2020-1-1 22:11+01:00", "2020-1-1 22:11 UTC", "does this help?"]
for datetime_string in check_this:
print(".........................")
print(f"This date time string '{datetime_string}' is in datetime iso format: {datetime_iso(datetime_string)}")
if datetime_iso(datetime_string):
print(f"Is it the UTC time zone? {utc_timezone(datetime_string)}")

Related

Variable in request does not update during while loop

I initialize a date variable and a now variable.
While date is smaller than now the code loops.
import ccxt
import datetime
exchange = ccxt.binance({ 'enableRateLimit': True })
date = 1502928000
now = int(round(datetime.datetime.timestamp(now)))
while date <= now:
ohlcv = exchange.fetch_ohlcv('BTC/USDT', '1d', date, 1)
print(ohlcv)
date += 86400
print(date)
At then end of the loop I update the date with one day, this works because I print the date and confirm the date changed.
But, the date within the request stays the same value. The response is always:
[[1502928000000, 4261.48, 4485.39, 4200.74, 4285.08, 795.150377]]
[[1502928000000, 4261.48, 4485.39, 4200.74, 4285.08, 795.150377]]
[[1502928000000, 4261.48, 4485.39, 4200.74, 4285.08, 795.150377]]
[[1502928000000, 4261.48, 4485.39, 4200.74, 4285.08, 795.150377]]
...
How do I update the date variable within the request?
Thank you

Custom date format in KQL

I would like to know if there is a possibility to customize the format of a specific datetime in KQL.
For example I have the following code:
let value = format_datetime(datetime(07:30:00), "HH:mm");
print value
As a result we obtain 07:30
My question here is that instead of having 07:30, is there a possibility to format it in a way to have a value = 7hr 30m
based on if your input is a datetime or a timespan value, you can try either of the following options (using some string manipulation):
print ts = timespan(07:30:00)
| project output = strcat(toint(ts/1h), "hr ", toint(ts/1m)%60, "min")
print dt = datetime(2021-02-16 07:30:00)
| project output = strcat(datetime_part("hour", dt), "hr ", datetime_part("minute", dt), "min")

Convert python list into datetime format to extract months from it

I have a date in the form of a list in python, which I need to convert to datetime format so that I can get month from it. But I am getting the error:
ValueError: time data "['2019-06-27']" does not match format '%Y-%m-%d'
for i, e in reversed(list(enumerate(dates_list))):
if dates_list[i][0] == 'Monday':
print(dates_list[i][1])
weekstart.append(dates_list[i][1])
format_str = '%Y-%m-%d'
datetime_obj = datetime.datetime.strptime(str(weekstart), format_str)
m = datetime_obj.strftime("%m")
dates_list:
[('Monday', '2019-06-24'), ('Tuesday', '2019-06-25'), ('Wednesday', '2019-06-26'), ('Thursday', '2019-06-27'), ('Friday', '2019-06-28'), ('Saturday', '2019-06-29'), ('Sunday', '2019-06-30')]
weekstart: 2019-06-24
Can someone help me to get a month out of weekstart?
weekstart = None
for i, e in reversed(list(enumerate(dates_list))):
if dates_list[i][0] == 'Monday':
print(dates_list[i][1])
weekstart = dates_list[i][1]
if weekstart:
format_str = '%Y-%m-%d'
datetime_obj = datetime.datetime.strptime(weekstart, format_str)
m = datetime_obj.strftime("%m")

Convert time in milliseconds to date format (YYYY-MM-DD) in Groovy

Is there a function to convert time in milliseconds to date format (YYYY-MM-DD) in Groovy?
I have a Groovy script which needs to compare to date values as follows:
for(i in order_lineitems)
{
if(i.startDate==order_submit_date)
{
matchedIds1 += i.salesOrderLineitemId+',';
}
}
Here i.startDate has time in milliseconds of the date format yyyy-mm-dd whereas order_submit_date has the time in milliseconds in the date format yyyy-MM-dd HH:mm:ss. I need to convert order_submit_date into this format yyyy-mm-dd within the if block itself.
I am new to the Groovy script and I need help here.
There was a small mistake in my code. I corrected it.
The if block should be as follows if (i.startDate == order_submit_date) and both are long values represented in millis.
Now I need to make sure the condition is right i.e. start date is equal to order submit date.
Here what is happening is :
i.startDate has the value 1452105000000 (Thu Jan 07 2016 00:00:00) which is been stored in the DB when a Sales Order is created
and order_submit_date has the value 1452158393097 (Thu Jan 07 2016 14:49:53) which is being genertaed on the flow when a user submits the Sales order for approvals in the UI.
Now since order_sbmit_date has both date and time the long value is different and am unable to satisfy the condition.
Hence now i have a question as to wether there a function in groovy which would convert my order_submit_date long value to Date(yyyy-mm-dd) format and then compare both the values so as to satisfy the if block.
You can compare your dates in millis like this:
Notice that solutions depend on timezone.
Groovy option:
def compare(def m1, def m2) {
def dateInMillis1 = new Date(m1)
def dateInMillis2 = new Date(m2)
dateInMillis1.clearTime() == dateInMillis2.clearTime()
}
Java option 1:
boolean compare1(long millis1, long millis2) {
Date dateFromMillis = new Date(millis1);
Date dateFromMillis2 = new Date(millis2);
SimpleDateFormat sdf = new SimpleDateFormat("YYYY-MM-DD");
sdf.format(dateFromMillis).equals(sdf.format(dateFromMillis2));
}
or you can use Calendar:
Java option 2:
boolean compare2(long m1, long m2) {
Calendar calendar1 = Calendar.getInstance();
calendar1.setTimeInMillis(m1);
Calendar calendar2 = Calendar.getInstance();
calendar2.setTimeInMillis(m2);
return calendar1.get(Calendar.YEAR) == calendar2.get(Calendar.YEAR) &&
calendar1.get(Calendar.MONTH) == calendar2.get(Calendar.MONTH) &&
calendar1.get(Calendar.DAY_OF_MONTH) == calendar2.get(Calendar.DAY_OF_MONTH);
}
Your question is not clear that whether your dates are in string format or in milliseconds (long).
If dates are in string format like "2015-10-31"
You can use SimpleDateFormat for this.
import java.text.SimpleDateFormat
...
SimpleDateFormat dateParser = new SimpleDateFormat("yyyy-MM-dd")
SimpleDateFormat dateTimeParser = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
for (i in order_lineitems) {
if (dateParser.parse(i.startDate) >= dateTimeParser.parse(order_submit_date)) {
matchedIds1 += i.salesOrderLineitemId+',';
}
}
If dates are in milliseconds:
for (i in order_lineitems) {
if (new Date(i.startDate.toString().toLong()) >= new Date(order_submit_date.toString().toLong())) {
matchedIds1 += i.salesOrderLineitemId+',';
}
}
Note: Capital Y and small y (similarly for m & h) matterns in terms of formatting so please be clear about the usage.
Actual Answer to the Question:
You don't need any of the above solution instead you can simply use the clearTime() method on the date like below:
for (i in order_lineitems) {
if (new Date(i.startDate) >= new Date(order_submit_date).clearTime()) {
matchedIds1 += i.salesOrderLineitemId+',';
}
}
The clearTime() method will simply remove the time part from your date i.e. will convert Thu Jan 07 2016 14:49:53 to Thu Jan 07 2016 00:00:00`
What are type for i.startDate and order_submit_date java.util.Date? or String?
And do you want use i.startDate and order_submit_date only to do compare?
-- updated --
ok, then maybe like folowing?
import java.text.SimpleDateFormat
String startDate = "2016-01-20"
String order_submit_date = "2016-01-20 12:34:56"
SimpleDateFormat formatDateWithTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
SimpleDateFormat formatDate = new SimpleDateFormat("yyyy-MM-dd")
if (formatDate.parse(startDate) >= formatDateWithTime.parse(order_submit_date)) {
println "hehe"
} else {
println "hoho"
}
SimpleDateFormat#parse() returns java.util.Date.
Also you can compare with these.
You can also write like follows!
import java.text.SimpleDateFormat
SimpleDateFormat formatDateWithTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
SimpleDateFormat formatDate = new SimpleDateFormat("yyyy-MM-dd")
def matchedIds1 = order_lineitems.findAll {
formatDate.parse(it.startDate) >= formatDateWithTime.parse(order_submit_date)
}.join(",")
Long(type) version
def matchedIds1 = order_lineitems.findAll {
new Date(it.startDate).clearTime() == new Date(order_submit_date).clearTime()
}.join(",")
Long(type) without clearTime version
String format = "yyyy-MM-dd 00:00:00"
SimpleDateFormat fillByZero = new SimpleDateFormat(format)
def matchedIds1 = order_lineitems.findAll {
Date a = new Date(it.startDate)
Date b = new Date(order_submit_date)
fillByZero.parse(a.format(format)) == fillByZero.parse(b.format(format))
}.join(",")

Groovy : Dates not being calculated correctly? Using TimeCategory

can anyone tell me why these aren't being calculated correctly. I'm trying to add 1 second to the time and it seems to be adding 60 milliseconds when I apply formatting?
import java.text.*
import java.util.*
import groovy.time.TimeCategory
def xmlSlurper = new groovy.util.XmlSlurper()
// Get the previous total for number of journals
def journalCountProp = testRunner.testCase.getTestStepByName("Properties")
def journalCountTotal = journalCountProp.getPropertyValue( "journalCount" )
log.info " 1. Previous JournalCount from last run: "+journalCountTotal
def lastDateProp = testRunner.testCase.getTestStepByName("Properties")
def lastDateHolder = lastDateProp.getPropertyValue( "journalQueryDate" )
log.info " 2. Previous lastDate from last run: "+lastDateHolder
// Get the response for a given timeline
def response = xmlSlurper.parseText(context.expand('${GET Journal using JournalDate#Response}'));
def currentJournalCount = response.Journals.Journal.size()
log.info " 3. Number of Journals in this Run: "+currentJournalCount
//Getting the date from the last Journal (including an offset as the array count starts at 0)
def lastDate = response.Journals.Journal[currentJournalCount-1].CreatedDateUTC
log.info " 4. CreatedDate from last journal in this response: "+lastDate
//log.info response.Journals.Journal[currentJournalCount-1].CreatedDateUTC
def newdate = Date.parse("yyyy-MM-dd'T'HH:mm:ss.mmm",lastDate.toString())
log.info "dateBeforeChange: "+newdate.format("yyyy-MM-dd'T'HH:mm:ss.mmm")
use(TimeCategory){
newdate = newdate+1.seconds
}
log.info "date After Change: "+newdate.format("yyyy-MM-dd'T'hh:mm:ss.mmm")
log.info " 5. "+newdate.format("yyyy-MM-dd'T'HH:ss:mmm")
OUTPUT:
CreatedDate from last journal in this response: 2007-03-29T23:19:52.073
dateBeforeChange: 2007-03-30T00:13:52.013
date After Change: 2007-03-30T12:13:53.013
I can't figure it out?!!
Cheers,
- Richard
HH means "hour in a day (0-23)", whereas hh means "hour in am/pm (1-12)".
See the SimpleDateFormat ApiDoc for a reference (SimpleDateFormat is used under the hood).

Resources