How do I take time away from a time in datetime? - python-3.7

I am working on a project that can take on time away from another time and tell me the waiting time. Eg:
10:43:56 - 10:39:46 = 4 minutes 10 seconds.
I've tried to use multiple libraries which of none have worked. After that I resorted to online tutorials with datetime as it seemed to be the closest one to what I am looking for.
import datetime
a = "9:54:34"
b = "9:52:34"
print(datetime.timedelta(a, b))
I was looking to see if there is a function along the lines of datetime.timedeltasubtract(a, b) but thats not a thing. Help would be appreciated, please ignore my lack of skill..
I was expecting the output to be 00:02:00 or 2 or 2 minutes. But the error was
Traceback (most recent call last): File "C:/Users/photo/Desktop/CJ
work project/main.py", line 7, in
print(datetime.timedelta(a, b)) TypeError: unsupported type for timedelta seconds component: str

As first step is necessary to convert the strings to datetime objects using datetime.strptime function (doc). Then you can subtract these two times:
import datetime
a = "9:54:34"
b = "9:52:34"
d1 = datetime.datetime.strptime(a,'%H:%M:%S')
d2 = datetime.datetime.strptime(b,'%H:%M:%S')
print(d1 - d2)
Prints:
0:02:00

Related

How to calculate the next minute and next 5 minute intevals given a ZonedDateTime

I have a instance of a ZonedDatetime.
ZonedDateTime.now(ZoneId.of("America/New_York"))
I basically need a function that will take an instance of a ZonedDateTime and return the next 1 minute and 5 minute values.
So if the current time is:
2021-10-24T19:46:10.649817
The next minute will be 19:47:00 and the next 5 minute will be 19:50:00
The next 5 minute interval is always like:
1:00
1:05
1:10
1:15
1:20
1:25
...
1:50
1:55
2:00
i.e. the next 5 minute interval is not based on exactly 5 minutes from now, but rather the next 5 minutes based on starting from the beginning of the hour. Same goes for the next 1 minute interval in the future.
def nextIntervals(zdt: ZonedDateTime): (ZonedDateTime, ZonedDateTime) = {
???
}
It is fairly simple to do so without hardcoding the values. Unfortunately I'm not familiar with scala so I'll give you some pseudo code, I believe you'll be able to easily translate it.
nextIntervals(zdt) {
timestamp = zdt.toUnixTimestamp();
return [
new ZonedDateTime(timestamp + (60 - timestamp % 60)),
new ZonedDateTime(timestamp + (300 - timestamp % 300))
]
}
The above code assumes that ZonedDateTime can be instantiated by giving it a unix timestamp, measured in seconds. And also that it can be converted to a unix timestamp.
The idea is pretty simple: the remainder of the modulus will be the time that has elapsed since the last required period (in your case 1 minute or 5 minutes). Take that away from the period itself and you have the time that's left until the next period. Add that to the current time and you have the exact datetime.
Edit:
Here's a working javascript example
function nextIntervals(date) {
let t = date.getTime();
return [
60e3,
300e3,
].map(i => new Date(t + i - t % i));
}
console.log(nextIntervals(new Date));
You can use the following functions to meet your requirements:
ZonedDateTime#plusMinutes
ZonedDateTime#minusMinutes
ZonedDateTime#truncatedTo
Demo:
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.temporal.ChronoUnit;
public class Main {
public static void main(String[] args) {
ZonedDateTime now = ZonedDateTime.now(ZoneId.of("America/New_York"));
ZonedDateTime nextMinute = now.plusMinutes(1).truncatedTo(ChronoUnit.MINUTES);
ZonedDateTime nextMultipleOfFiveMin = now.truncatedTo(ChronoUnit.MINUTES)
.minusMinutes(now.getMinute() % 5)
.plusMinutes(5);
System.out.println(now);
System.out.println(nextMinute);
System.out.println(nextMultipleOfFiveMin);
}
}
Output from a sample run:
2021-10-25T16:59:22.662943-04:00[America/New_York]
2021-10-25T17:00-04:00[America/New_York]
2021-10-25T17:00-04:00[America/New_York]
Output from another sample run after a while:
2021-10-25T17:05:09.596952-04:00[America/New_York]
2021-10-25T17:06-04:00[America/New_York]
2021-10-25T17:10-04:00[America/New_York]
ONLINE DEMO
Learn more about the modern Date-Time API from Trail: Date Time. Check this answer and this answer to learn how to use java.time API with JDBC.
Note: The java.util Date-Time API and their formatting API, SimpleDateFormat are outdated and error-prone. It is recommended to stop using them completely and switch to the modern Date-Time API*.
* If you are working for an Android project and your Android API level is still not compliant with Java-8, check Java 8+ APIs available through desugaring. Note that Android 8.0 Oreo already provides support for java.time.
We do need a little bit of hand-coded math to handle the 5-minute interval case. Excuse my Java syntax.
ZonedDateTime now = ZonedDateTime.now(ZoneId.of("America/New_York"));
System.out.println("Now: " + now);
// Truncate to the previous 5 minutes
ZonedDateTime zdt = now.truncatedTo(ChronoUnit.MINUTES);
zdt = zdt.withMinute(zdt.getMinute() / 5 * 5);
for (int i = 0; i <= 12; i++) {
zdt = zdt.plusMinutes(5);
System.out.println(zdt);
}
Example output:
Now: 2021-10-25T15:23:31.357567-04:00[America/New_York]
2021-10-25T15:25-04:00[America/New_York]
2021-10-25T15:30-04:00[America/New_York]
2021-10-25T15:35-04:00[America/New_York]
2021-10-25T15:40-04:00[America/New_York]
2021-10-25T15:45-04:00[America/New_York]
2021-10-25T15:50-04:00[America/New_York]
2021-10-25T15:55-04:00[America/New_York]
2021-10-25T16:00-04:00[America/New_York]
2021-10-25T16:05-04:00[America/New_York]
2021-10-25T16:10-04:00[America/New_York]
2021-10-25T16:15-04:00[America/New_York]
2021-10-25T16:20-04:00[America/New_York]
2021-10-25T16:25-04:00[America/New_York]
The trick to truncate to a whole multiple of 5 minutes is to divide by 5, obtain a whole number and discard any remainder, and multiply by 5 again.
The 1-minute interval is similar, only a bit simpler: we don’t need to do any math ourselves, java.time takes care of it all.

Get date out of year and day of year from a value - Scala

I have a 6 digit value from which i have to get the date in scala. For eg if the value is - 119003 then the output should be
1=20 century
19=2019 year
003= january 3
The output should be 2019/01/03
I have tried ti split the value first and then get the date. But i am not sure how to proceed as i am new to scala
I think you'll have to do the century calculations manually. After that you can let the java.time library do all the rest.
import java.time.LocalDate
import java.time.format.DateTimeFormatter
val in = "119003"
val cent = in.head.asDigit + 19
val res = LocalDate.parse(cent+in.tail, DateTimeFormatter.ofPattern("yyyyDDD"))
.format(DateTimeFormatter.ofPattern("yyyy/MM/dd"))
//res: String = 2019/01/03
The Date class of Java 1.0 used 1900-based years, so 119 would mean 2019, for example. This use was deprecated already in Java 1.1 more than 20 years ago, so it’s surprising to see it survive into Scala.
When you say 6 digit value, I take it to be a number (not a string).
The answer by jwvh is correct. My variant would be like (sorry about the Java code, please translate yourself):
int value = 119003;
int year1900based = value / 1000;
int dayOfYear = value % 1000;
LocalDate date = LocalDate.ofYearDay(year1900based + 1900, dayOfYear);
System.out.println(date);
2019-01-03
If you’ve got a string, I would slice it into two parts only, 119 and 003 (not three parts as in your comment). Parse each into an int and proceed as above.
If you need 2019/01/03 format in your output, use a DateTimeFormatter for that. Inside your program, do keep the LocalDate, not a String.

Find number of days between two given dates in Rcpp

I'm newbie in Rcpp, but I have a task which's connected with Date and Datetime.
Let me have market data in DataFrame in my Rcpp function. So, Date field has formatting like this:
2016-04-19 00:01:00
Dataframe field name which contains Date values is "Date". So, I get 2 vectors:
DatetimeVector datetime = df["Date"];
DateVector pureDate = df["Date"];
Problems:
1) I can't take difference between 2 Date values of Date (I don't know why, but gcc-4.9.3 gives me an error on difference like this:
Date pureDay = pureDate[0];
auto tmp = pureDate[j+1] - pureDay;
error: ambiguous overload for 'operator-' (operand types are
'Rcpp::traits::storage_type<14>::type {aka double}' and 'Rcpp::Date')
auto tmp = tmpDate[j+1] - tmpTradeDay;
But if I use code like this:
Date pureDay = pureDate[0];
auto tmp = pureDate[j+1] - pureDate[j];
It works well.
2) How it possible to format an output for Date and Datetime objects? to_string won't format it well - I give a result like this: 1461176460.000000
3) I expected that syntax like Date(datetime[i]) will give me a Date object. But it won't. I know that pureDate[1] - pureDate[0] should have the same Y-M-D value, but they differ for series lag (60 seconds).
Thnxs. Could anyone helps me with these problems?
You seem a little lost, and there are really multiple questions in this one.
Question 1) will give a short example below.
Question 2) is mostly about formatting, you may want to look into the class documentation and header; both Date and Datetime have a format() method that works just like the R equivalent or C library function for date(time) formating, the fabled strftime().
Question 3) is unclear; I am not sure what you are asking. Maybe the answer to question 1) below helps.
Simple example for question 1:
#include <Rcpp.h>
using namespace Rcpp;
// [[Rcpp::export]]
double question1(DateVector dv) {
double d = dv[1] - dv[0];
return d;
}
/*** R
set.seed(123)
datevector <- Sys.Date() + cumsum(runif(3)*30);
datevector
diff(datevector)
question1(datevector)
*/
and its outcome:
R> Rcpp::sourceCpp("/tmp/datequestion.cpp")
R> set.seed(123)
R> datevector <- Sys.Date() + cumsum(runif(3)*30);
R> datevector
[1] "2018-03-28" "2018-04-21" "2018-05-03"
R> diff(datevector)
Time differences in days
[1] 23.6492 12.2693
R> question1(datevector)
[1] 23.6492
R>
Same answer as from R. Your code still has an index calculation, that sometimes confuses the compiler. Making it simpler (ie more steps) often helps.
Lastly, maybe look at some Rcpp documentation and examples. The RcppExamples package has a function on dates and datetimes ...

MATLAB Yahoo Finance fetch gives a bizarre date format

Here's my chunk of code
y = yahoo;
% get some data for Apple
from = '2014-01-01';
to = '2016-04-01';
aapl = fetch(y,'AAPL','Adj Close', from, to);
close(y)
I get two columns - the second are the prices, the first are... Date values? But they cannot be! I expected Unix dates, but my dates start with 1455950 and a conversion gives me:
>> datetime(1455950, 'convertFrom', 'posixtime')
ans =
17-Jan-1970 20:25:50
So that clearly cannot be it. Also, what's crazy is if I get today's date, I get an even smaller value:
>> fetch(y, 'AAPL', 'Date')
ans =
Date: 736449
Can someone help me understand this madnesss?
As it turns out, yahoo was simply giving out false values. All working now, and datetime(x, 'convertfrom', 'datenum') works perfectly as can be seen here.

subtracting a DateTime from a DateTime in scala

I'm relatively new to both scala and jodatime, but have been pretty impressed with both. I'm trying to figure out if there is a more elegant way to do some date arithmetic. Here's a method:
private def calcDuration() : String = {
val p = new Period(calcCloseTime.toInstant.getMillis - calcOpenTime.toInstant.getMillis)
val s : String = p.getHours.toString + ":" + p.getMinutes.toString +
":" + p.getSeconds.toString
return s
}
I convert everything to a string because I am putting it into a MongoDB and I'm not sure how to serialize a joda Duration or Period. If someone knows that I would really appreciate the answer.
Anyway, the calcCloseTime and calcOpenTime methods return DateTime objects. Converting them to Instants is the best way I found to get the difference. Is there a better way?
Another side question: When the hours, minutes or seconds are single digit, the resulting string is not zero filled. Is there a straightforward way to make that string look like HH:MM:SS?
Thanks,
John
Period formatting is done by the PeriodFormatter class. You can use a default one, or construct your own using PeriodFormatterBuilder. It may take some more code as you might like to set this builder up properly, but you can use it for example like so:
scala> import org.joda.time._
import org.joda.time._
scala> import org.joda.time.format._
import org.joda.time.format._
scala> val d1 = new DateTime(2010,1,1,10,5,1,0)
d1: org.joda.time.DateTime = 2010-01-01T10:05:01.000+01:00
scala> val d2 = new DateTime(2010,1,1,13,7,2,0)
d2: org.joda.time.DateTime = 2010-01-01T13:07:02.000+01:00
scala> val p = new Period(d1, d2)
p: org.joda.time.Period = PT3H2M1S
scala> val hms = new PeriodFormatterBuilder() minimumPrintedDigits(2) printZeroAlways() appendHours() appendSeparator(":") appendMinutes() appendSuffix(":") appendSeconds() toFormatter
hms: org.joda.time.format.PeriodFormatter = org.joda.time.format.PeriodFormatter#4d2125
scala> hms print p
res0: java.lang.String = 03:02:01
You should perhaps also be aware that day transitions are not taken into account:
scala> val p2 = new Period(new LocalDate(2010,1,1), new LocalDate(2010,1,2))
p2: org.joda.time.Period = P1D
scala> hms print p2
res1: java.lang.String = 00:00:00
so if you need to hanldes those as well, you would also need to add the required fields (days, weeks, years maybe) to the formatter.
You might want to take a look at Jorge Ortiz's wrapper for Joda-Time, scala-time for something that's a bit nicer to work with in Scala.
You should then be able to use something like
(calcOpenTime to calcCloseTime).millis
Does this link help?
How do I calculate the difference between two dates?
This question has more than one answer! If you just want the number of whole days between two dates, then you can use the new Days class in version 1.4 of Joda-Time.
Days d = Days.daysBetween(startDate, endDate);
int days = d.getDays();
This method, and other static methods on the Days class have been designed to operate well with the JDK5 static import facility.
If however you want to calculate the number of days, weeks, months and years between the two dates, then you need a Period By default, this will split the difference between the two datetimes into parts, such as "1 month, 2 weeks, 4 days and 7 hours".
Period p = new Period(startDate, endDate);
You can control which fields get extracted using a PeriodType.
Period p = new Period(startDate, endDate, PeriodType.yearMonthDay());
This example will return not return any weeks or time fields, thus the previous example becomes "1 month and 18 days".