Expression.Error: We cannot convert a value of type Function to type Text - formula

This M (Power Query) function gives this error "Expression.Error: We cannot convert a value of type Function to type Text."
The Function Objective is having two Text Input and subtracting them to durations (as list or text)
For Example:
1/20/2020 1:49:46 PM, 1/20/2020 1:58:03 PM, 1/20/2020 2:09:42 PM
1/20/2020 1:49:41 PM, 1/20/2020 1:57:58 PM, 1/20/2020 2:09:38 PM
let
Source = (txtCheckInTime as text, txtCheckOutTime as text) as text =>
let
lstCheckinTimeLst = Text.Split(txtCheckInTime, ", "),
lstCheckOutTimeLst = Text.Split(txtCheckOutTime, ", "),
txtCheckInEvent = each lstCheckinTimeLst,
txtCheckOutEvent = each lstCheckOutTimeLst,
EventDuration = DateTime.FromText(txtCheckInEvent) - DateTime.FromText(txtCheckOutEvent),
Source = Text.Combine(Duration.ToText(EventDuration), ", ")
in
Source
in
Source
Could anyway point out the error?

There are a couple of issues going on here.
The main issue is because the each keyword is a placeholder for an iterative function, not an iterator itself (see here for details).
The DateTime.FromText() function requires a single element, not a list or function object (see here for details).
It appears like in your sample data, the CheckInTime's are after the CheckOutTime's?
If I were to re-write your function, this is what it would look like:
let fun_GetDurations = (txt_CheckInTime as text, txt_CheckOutTime as text) as text =>
let
lst_CheckInTime = Text.Split(txt_CheckInTime, ", "),
lst_CheckOutTime = Text.Split(txt_CheckOutTime, ", "),
tbl_Times = Table.FromColumns({lst_CheckInTime, lst_CheckOutTime}, {"CheckInTime", "CheckOutTime"}),
fix_Formatting = Table.TransformColumns(tbl_Times, {{"CheckInTime", each DateTime.FromText(_, "en-US"), type nullable text}, {"CheckOutTime", each DateTime.FromText(_, "en-US"), type nullable text}}),
add_Duration = Table.AddColumn(fix_Formatting, "Duration", each Duration.ToText([CheckOutTime] - [CheckInTime]), type text),
get_Durations = Text.Combine(Table.Column(add_Duration, "Duration"), ", ")
in
get_Durations
in fun_GetDurations
And then when you check it:
let
txt_CheckInTime = "1/20/2020 1:49:41 PM, 1/20/2020 1:57:58 PM, 1/20/2020 2:09:38 PM",
txt_CheckOutTime = "1/20/2020 1:49:46 PM, 1/20/2020 1:58:03 PM, 1/20/2020 2:09:42 PM",
Durations = fun_GetDurations(txt_CheckInTime, txt_CheckOutTime)
in
Durations
You get the results expected:
00:00:05, 00:00:05, 00:00:04

Related

python: How to create a dictionary from two files

import os
d = {}
with open("time.txt") as f:
for line in f:
(key, val) = line.split()
d[int(key)] = val
print (d)
I have days.txt and time.txt so how to create dictionary from the two file.
days.txt
Mo Tu We Th Fr
time.txt
19:00 18:00 16:00 20:00 23:00
My expected output is
"Mo": 19:00
"Tu": 18:00
"We": 16:00
"Th": 20:00
"Fr": 23:00
I edited your code and put the comments so you can understand:
import os
d = {}
#opening and reading the words from days.txt
days = open("days.txt", 'r').read().split(" ")
#added reading mode to the open function
with open("time.txt", "r") as f:
#Gives an array that reads each word separated by space
f = f.read().split(' ')
#parsing the list by ids is better in my opinion
for i in range(len(f)):
#adding the i element of days to the dict and element i of f as the value
d[days[i]] = f[i]
print(d)
See below. Read the 2 files - zip the data and generate a dict
with open('time.txt') as f1:
t = f1.readline().split()
with open('days.txt') as f2:
d = f2.readline().split()
data = dict(p for p in zip(d,t))
print(data)
output
{'Mo': '19:00', 'Tu': '18:00', 'We': '16:00', 'Th': '20:00', 'Fr': '23:00'}

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}')

Getting one hour less in time when converting to UTC via moment - utcOffset not working

When converting time to UTC its showing one hour less than expected
I am updating a variable of dot net via moment to convert the time & show local system time to user. But post conversion i am getting one hour less. Tried utcOffset but getting error utcOffset is not a function. any suggestion
Where formData.SubmittedDate = "6/7/2019 5:44:59 AM"
$('[data-utcdate]').each(function () {
var d = moment($(this).attr('data-utcdate'));
//var isDST = d.utc().local().isDST();
//var d = moment(d).utcOffset(d);
d = d.utc();
$(this).html(d.format('MMM D, YYYY h:mm A'));
})
Getting :Jun 7, 2019 12:14 AM
Expected : Jun 7, 2019 11:44 AM
From the docs:
Get the UTC offset in minutes.
So you could use a manipulation method like add with it:
$('[data-utcdate]').each(function () {
var d = moment($(this).attr('data-utcdate'));
var offset = d.utcOffset() // will return the offset in minutes
var time = d.add(offset, "m");
$(this).html(time.format('MMM D, YYYY h:mm A'));
})

Format datetime day with st, nd, rd, th

I'm creating a report in SSRS and across the top I have a header with a placeholder for "Last Refreshed" which will show when the report last ran.
My function in the placeholder is simply this:
=Format(Now, "dddd dd MMMM yyyy hh:mm tt")
Which looks like this:
Monday 22 September 2015 09:46 AM
I want to format the day value with the English suffix of st, nd, rd and th appropriately.
I can't find a built in function for this and the guides I've looked at so far seem to describe doing it on the SQL side with stored procedures which I don't want. I'm looking for a report side solution.
I thought I could get away with an ugly nested IIF that did it but it errors out despite not giving me any syntax errors (whitespace is just for readability).
=Format(Now, "dddd " +
IIF(DAY(Now) = "1", "1st",
IIF(DAY(Now) = "21","21st",
IIF(DAY(Now) = "31","31st",
IIF(DAY(Now) = "2","2nd",
IIF(DAY(Now) = "22","22nd",
IIF(DAY(Now) = "3","3rd",
IIF(DAY(Now) = "23","23rd",
DAY(Now) + "th")))))))
+ " MMMM yyyy hh:mm tt")
In any other language I would have nailed this ages ago, but SSRS is new to me and so I'm not sure about how to do even simple string manipulation. Frustrating!
Thanks for any help or pointers you can give me.
Edit: I've read about inserting VB code into the report which would solve my problem, but I must be going nuts because I can't see where to add it. The guides say to go into the Properties > Code section but I can't see that.
Go to layout view. Select Report Properties.Click on the "Code" tab and Enter this code
Public Function ConvertDate(ByVal mydate As DateTime) as string
Dim myday as integer
Dim strsuff As String
Dim mynewdate As String
'Default to th
strsuff = "th"
myday = DatePart("d", mydate)
If myday = 1 Or myday = 21 Or myday = 31 Then strsuff = "st"
If myday = 2 Or myday = 22 Then strsuff = "nd"
If myday = 3 Or myday = 23 Then strsuff = "rd"
mynewdate = CStr(DatePart("d", mydate)) + strsuff + " " + CStr(MonthName(DatePart("m", mydate))) + " " + CStr(DatePart("yyyy", mydate))
return mynewdate
End function
Add the following expression in the required field. I've used a parameter, but you might be referencing a data field?
=code.ConvertDate(Parameters!Date.Value)
Right Click on the Textbox, Go To Textbox Properties then, Click on Number tab, click on custom format option then click on fx button in black.
Write just one line of code will do your work in simpler way:
A form will open, copy the below text and paste there to need to change following text with your database date field.
Fields!FieldName.Value, "Dataset"
Replace FieldName with your Date Field
Replace Dataset with your Dateset Name
="d" + switch(int(Day((Fields!FieldName.Value, "Dataset"))) mod
10=1,"'st'",int(Day((Fields!FieldName.Value, "Dataset"))) mod 10 =
2,"'nd'",int(Day((Fields!FieldName.Value, "Dataset"))) mod 10 =
3,"'rd'",true,"'th'") + " MMMM, yyyy"
I found an easy way to do it. Please see example below;
= DAY(Globals!ExecutionTime) &
SWITCH(
DAY(Globals!ExecutionTime)= 1 OR DAY(Globals!ExecutionTime) = 21 OR DAY(Globals!ExecutionTime)=31, "st",
DAY(Globals!ExecutionTime)= 2 OR DAY(Globals!ExecutionTime) = 22 , "nd",
DAY(Globals!ExecutionTime)= 3 OR DAY(Globals!ExecutionTime) = 23 , "rd",
true, "th"
)

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