moment duration error formatting with moment-duration-format - momentjs

I have a problem with the formatting using moment-duration-format. I'm passing the format 'y[y] M[m] w[w] d[d] h[hr] m[min]' inside format.
But I'm getting hrs and mins instead of hr and min as the output.
eg : Im getting 1m 0w 3d 22hrs 30mins as the output.
But what I need as output is 1m 0w 3d 22hr 30min

Try updating the locale info to the format that you want. This might help you get started.
https://codesandbox.io/s/compassionate-bas-fg1c2?file=/src/index.js
var moment = require("moment");
require("moment-duration-format");
moment.updateLocale("sample", {
durationLabelsStandard: {
s: "singular second",
ss: "first plural seconds",
sss: "next plural seconds"
},
durationLabelsShort: {
s: "singular sec",
ss: "first plural secs",
sss: "next plural secs"
}
});
console.log(
moment
.duration(76800006, "seconds")
.format("y[y] M[m] w[w] d[d] h[hr] m[min]", {
locale: "sample"
})
);

Related

How to find and print a dictionary key/value that matches user input?

I need to print a dictionary value that matches the input of the user. For example, if the user enters the course number CS101 the output will look like:
The details for CS101 are:
Room: 3004
Instructor: Haynes
Time: 8:00 a.m.
However, if the user enters an incorrect/invalid course number, I need to print out a message letting them know:
CS101 is an invalid course number.
I have tried if, for loops, and while loops. The problem is, every time I get the course info printed, the invalid course number message won't display because of KeyError. On the other hand, if I happen to "fix" the error message, then the course number info won't print out and instead will return a NameError / TypeError.
I will be honest, I have struggled for some time now with this, and I feel as though I am either assigning something incorrectly or printing incorrectly. But I am a beginner and I don't have a great grasp on Python yet, which is why I am asking for help.
Unfortunately, I am not allowed to create one entire dictionary to group everything in (which would have been easier for me), but instead, I have to create 3 dictionaries.
This is the code:
room = {}
room["CS101"] = "3004"
room["CS102"] = "4501"
room["CS103"] = "6755"
room["NT110"] = "1244"
room["CM241"] = "1411"
instructor = {}
instructor["CS101"] = "Haynes"
instructor["CS102"] = "Alvarado"
instructor["CS103"] = "Rich"
instructor["NT110"] = "Burkes"
instructor["CM241"] = "Lee"
time = {}
time["CS101"] = "8:00 a.m."
time["CS102"] = "9:00 a.m."
time["CS103"] = "10:00 a.m."
time["NT110"] = "11:00 a.m."
time["CM241"] = "1:00 p.m."
def info():
print(f'College Course Locater Program')
print(f'Enter a course number below to get information')
info()
get_course = input(f'Enter course number here: ')
print(f'----------------------------------------------')
course_num = get_course
number = course_num
name = course_num
meeting = course_num
if number in room:
if name in instructor:
if meeting in time:
print(f'The details for course {get_course} are: ')
print(f'Room: {number["room"]}')
print(f'Instructor: {name["instructor"]}')
print(f'Time: {meeting["time"]}')
else:
print(f'{course_num} is an invalid course number.')
I have also tried formatting dictionaries in this style:
time_dict = {
"CS101": {
"Time": "8:00 a.m."
},
"CS102": {
"Time": "9:00 a.m."
},
"CS103": {
"Time": "10:00 a.m."
},
"NT110": {
"Time": "11:00 a.m."
},
"CM241": {
"Time": "1:00 p.m."
},
}
I thank everyone in advance who has an advice, answer, or suggestions to a solution.
This code here is unnecessary, because you are essentially setting 4 variables all to the same value get_course:
course_num = get_course
number = course_num
name = course_num
meeting = course_num
This code here doesn't work because you are trying to find a key with string "room" in a dictionary that doesn't exist, and same with the other lines afterwards
print(f'Room: {number["room"]}')
print(f'Instructor: {name["instructor"]}')
print(f'Time: {meeting["time"]}')
I replaced the code above with this:
print(f'Room: {room[get_course]}')
print(f'Instructor: {instructor[get_course]}')
print(f'Time: {time[get_course]}')
This searches the dictionary variable room for the key get_course (ex. "CS101") and returns the value corresponding to that key. The same thing happens for the other lines, except with the dictionary instructor and the dictionary time.
Here is the final code:
room = {}
room["CS101"] = "3004"
room["CS102"] = "4501"
room["CS103"] = "6755"
room["NT110"] = "1244"
room["CM241"] = "1411"
instructor = {}
instructor["CS101"] = "Haynes"
instructor["CS102"] = "Alvarado"
instructor["CS103"] = "Rich"
instructor["NT110"] = "Burkes"
instructor["CM241"] = "Lee"
time = {}
time["CS101"] = "8:00 a.m."
time["CS102"] = "9:00 a.m."
time["CS103"] = "10:00 a.m."
time["NT110"] = "11:00 a.m."
time["CM241"] = "1:00 p.m."
def info():
print(f'College Course Locater Program')
print(f'Enter a course number below to get information')
info()
get_course = input(f'Enter course number here: ')
print(f'----------------------------------------------')
if get_course in room and get_course in instructor and get_course in time:
print(f'The details for course {get_course} are: ')
print(f'Room: {room[get_course]}')
print(f'Instructor: {instructor[get_course]}')
print(f'Time: {time[get_course]}')
else:
print(f'{get_course} is an invalid course number.')
Here is a test with the input "CS101":
College Course Locater Program
Enter a course number below to get information
Enter course number here: CS101
----------------------------------------------
The details for course CS101 are:
Room: 3004
Instructor: Haynes
Time: 8:00 a.m.
You could also do it like this. it'll probably take less time. The function is not very organize, try to organize it a little and it should work. I'm still not very familiar with adding codes on here.
course_info = {
'CS101': {
'Room': '3004',
'Instructor': 'Haynes',
'Time': '8:00 am'
},
'CS102': {
'Room': '4501',
'Instructor': 'Alvarado',
'Time': '9:00 a.m.'
},
'CS103': {
'Room': '6755',
'instructor': 'Rich',
'Time:': '10:00 am',
},
'NT110': {
'Room': '1244',
'instructor': 'Burkes',
'Time': '11:00 am'
},
'CM241': {
'Room': '1411',
'Instructor': 'Lee',
'Time': '1:00 pm'
},
}
get_course = input(f'Enter a course number: ')
try:
courses = course_info[get_course]
print(f'The details for for course {get_course} are: ')
print(f"Room: {courses['Room']}, Time: {courses['Time']},
Instructor: {courses['Instructor']}")
except KeyError:
print(f'Details not found for {get_course}')

MomentJS comparing Unix time with minutes and get difference

I need to find if currentDate time (unix) and lastFetchedTime(unix) is greater than 30 minutes in moment.js.
How can compare the subtracted value from 30 minutes in moment?
lastFetchedTime(unix) is equivalent to the previous Date.now()..
const now = moment(Date.now());
const lastFetched = 1598578706;
const checkTime = now.diff(lastFetched, 'minutes') > 30 ;
You can use momentJS duration function to get the difference between two times which are in unix format.
Firstly, you need to convert the unix format to human readable time and then get the difference of current time and lastFetched time using asMinutes function of duration
If the difference is greater then 30 then do something else or do something else.
Live Demo:
const now = moment().unix()
const lastFetched = 1598597404;
const duration = moment.duration(moment.unix(now).diff(moment.unix(lastFetched)));
const getMinutes = duration.asMinutes();
if (getMinutes > 30) {
console.log('Minutes are GREATER then 30 minutes - from now')
} else {
console.log('Minutes are LESS then 30 minutes - from now')
}
<script src="//cdnjs.cloudflare.com/ajax/libs/moment.js/2.8.4/moment.js"></script>

MomentJS not returning correct info

I have an ISO formatted date that isn't being converted to the correct time, and I can't figure out why.
const m = (() => {
console.log("Here is the original time: " + periods)
const timeFixed = moment(periods).format("dddd, MMMM Do YYYY, h:mm:ss ");
console.log("Here is the fixed time: " + timeFixed)
return timeFixed;
})();
Using this, returns this:
Here is the original time: 2020-08-12T08:52:55Z
Here is the fixed time: Wednesday, January 1st 2020, 12:00:00
Any help given is appreciated as always.
Solved it, weirdly. It seems Moment was having an issue with the incoming format. Converted it to a string, then it handled it.
const m = (() => {
console.log("Here is the original time: " + periods)
const timeString = new Date(periods);
const timeFixed = moment(timeString).format("dddd, MMMM Do YYYY, hh:mm:ss ");
console.log("Here is the fixed time: " + timeFixed)
return timeFixed;
})();
Resulted in:
Here is the original time: 2020-08-12T08:52:55Z
Here is the fixed time: Wednesday, August 12th 2020, 09:52:55
Yes the time zone is off, but that's another problem for another day. Thanks for helping me find it.

Getting the number ordinal with Moment.js

Is it possible to get a number's ordinal with Moment.js? For example if I pass in the number 7 and Momentjs would return '7th'
So far I have tried all these but none have worked
console.log(moment("12", "D Do")); // returns n {_isAMomentObject: true, _i: "12", _f: "D Do", _isUTC: false, _pf: Object…}
console.log(moment("3", "D Do")); // returns n {_isAMomentObject: true, _i: "3", _f: "D Do", _isUTC: false, _pf: Object…}
console.log(moment(3).format("D Do")); // returns '1 1st'
console.log(moment('3').format("D Do")); // returns '1 1st'
console.log(moment().day('3').format("Do")); // returns '9th'
console.log(moment().day(3).format("D Do")); // returns '9 9th'
EDIT: I should have mentioned that I am trying to process a date. So I get the date in this format DD-MM-YYYY. So if the date is 07-12-2015, I want to display it as 7th.
moment.localeData().ordinal(23)
// 23rd
I don't think Moment.js provides such an interface because it's use case is very limited.
If you don't have a date (e.g. a ranking) you could use the following:
function ordinal(number) {
switch (number) {
case 1:
case 21:
return number + 'st';
break;
case 2:
case 22:
return number + 'nd';
break;
case 3:
case 23:
return number + 'rd';
break;
default:
return number + 'th';
}
}
EDIT: Answer to the edited question:
You can do the following:
const date = '3-12-2015';
moment(date, 'DD-MM-YYYY').format('Do');
Demo
Documentation:
Parse: http://momentjs.com/docs/#/parsing/string-format/
Display: http://momentjs.com/docs/#/displaying/format/
Building off of the accepted answer above, you can avoid adding the day to an arbitrary date and instead just do:
moment('3', 'DD').format('Do');
EDIT
As pointed out in the comments, the above answer will return an invalid date for any number above 30, so a more stable solution that includes the 31st would be:
moment(`2012-10-${day}`).format('Do')

Python convert military time user input and calculate time worked (datetime.timedelta)

Noob here,
I'm stuck at trying to present user input in military time into standard time. The code works so far, but I need to subtract 12 hours from the end time to display in standard time. How do I do this using datetime.time? Also, do I need to convert the original user input to an integer to perform datetime.timedelta calculations? Previous questions don't seem to answer my coding questions.
My code is:
def timeconvert():
print "Hello and welcome to Python Payroll 1.0."
print ""
# User input for start time. Variable stored.
start = raw_input("Enter your check-in time in military format (0900): ")
# User input for end time. Variable stored.
end = raw_input("Enter your check-out time in military format (1700): ")
print ""
# ---------------------------------------------------------------------------
# Present user input in standard time format hhmm = hh:mm
# ---------------------------------------------------------------------------
import datetime, time
convert_start = datetime.time(hour=int(start[0:2]), minute=int(start[2:4]))
# need to find a way to subtract 12 from the hour to present end time in standard time
convert_end = datetime.time(hour=int(end[0:2]), minute=int(end[2:4]))
print 'You started at', convert_start.strftime("%H:%M"),'am', 'and ended at', convert_end.strftime("%H:%M"), 'pm'
# ---------------------------------------------------------------------------
# Use timedelta to caculate time worked.
# ---------------------------------------------------------------------------
# print datetime.timedelta
timeconvert()
raw_input("Press ENTER to exit program") # Closes program.
Thanks.
You can use strftime("%I:%M %p") to get standard 12 hour formatting with "AM" or "PM" at the end. See the Python documentation for more details on datetime string formatting.
Also, while it is not natively supported, you can simply use the two datetime.time instances to do your calculation as part of the timedelata constructor.
The below code should suffice, though proper error checking should definitely be used. ;)
--ap
start = raw_input("Enter your check-in time in military format (0900): ")
end = raw_input("Enter your check-out time in military format (1700): ")
# convert user input to datetime instances
start_t = datetime.time(hour=int(start[0:2]), minute=int(start[2:4]))
end_t = datetime.time(hour=int(end[0:2]), minute=int(end[2:4]))
delta_t = datetime.timedelta(
hours = (end_t.hour - start_t.hour),
minutes = (end_t.minute - start_t.minute)
)
# datetime format
fmt = "%I:%M %p"
print 'You started at %s and ended at %s' % (start_t.strftime(fmt), end_t.strftime(fmt))
print 'You worked for %s' % (delta_t)
def time12hr(string):
hours = string[:2]
minutes = string[2:]
x = " "
if int(hours) == 12:
x = "p.m."
hours = "12"
elif int(hours) == 00:
x = "a.m."
hours = "12"
elif int(hours) > 12:
x = "p.m."
hours = str(int(hours) - 12)
else:
x = "a.m."
return "%s:%s %s"%(hours ,minutes,x)
print time12hr('1202')
print time12hr('1200')
print time12hr('0059')
print time12hr('1301')
print time12hr('0000')

Resources