How to put colon inbetween elements of a big number using python - python-2.7

My question is my title . I want to put colon to number 2034820. It should look like 2:03:48:20
Basically this is my time data in HHMMSSMS format i.e hour minute second and millisecond.I want to plot other data with respect to this time format. How can I plot my data in y-axis and time of given format in x-axis.
data = numpy.genfromtxt('inputfile.dat') fig=plt.figure()
ax1 = plt.subplot(111) sat1=ax1.plot(data[:,1],'b',linewidth=1,label='SVID-127')
sat2 = ax1.plot(data[:,2],'m-',linewidth=1,label='SVID-128')
Any help is highly appreciated.
Thanks

you can parse the time with datetime.strptime and then re-format it:
from datetime import datetime
tme = datetime.strptime('{:08d}'.format(2034820), '%H%M%S%f').time()
strg = '{0:%H:%M:%S:%f}'.format(tme)
print(strg[:-4]) # cut the trailing '0000'
# 02:03:48:20
this assumes your input is an integer (which will be converted to a zero-padded string of length 8 with '{:08d}'.format(2034820); if the data comes as string you need to convert it to an int first: '{:08d}'.format(int('2034820'))).
from your comments: you seem to be getting the number of seconds that have passed since midnight. for those you could to this:
from datetime import time
def convert(timefloat):
hours, rest = divmod(timefloat, 3600)
mins, rest = divmod(rest, 60)
secs, rest = divmod(rest, 1)
microsecs = int(10**6 * rest)
tme = time(int(hours), int(mins), int(secs), microsecs)
return '{0:%H:%M:%S:%f}'.format(tme)[:-4]
which gives for your test-data:
for d in data:
print(convert(d))
#23:59:59:58
#23:59:59:80
#23:59:59:99
#00:00:00:20
#00:00:00:40
#00:00:00:60

Related

Problem with string to float conversion of values in pandas

My pandas dataframe column which have prices are mostly in the format r'\d+\.\d+' , which is what you expect. But when I try to convert it astype float, it says that I have got few numbers in the format \d+\.\d+\.\d+ like this one '6041.60.1'.
How do I go about converting all of them in the format \d+\.\d+ with series.str.replace()? The expected result is '6041.60'.
I'd recommand using .apply
df1["column"] = df1["column"].apply(lambda x: "".join(x.rsplit(".",1)), axis = 1 )#remove the last "."
df1["column"] = df1["column"].astype("float")

Trouble using utcoffset with Chart.js

I'm trying to use Chart.js with a datetime x axis, and I need to adjust all my values by subtracting 5 hours. Here's some of my code:
var timeFormat = 'MM/DD HH:mm';
time: {
format: timeFormat,
tooltipFormat: 'll',
parser: function(utcMoment) {
return moment(utcMoment).utcOffset(5, true);
}
},
Without the parser function, my values are normal (10:00, January 10, 2021), but with the parser function, for some reason my values are set back all the way to 2001. Yes two-thousand-and-one.(10:00, January 10, 2001) Note that the time is not actually changed (So two errors: 1.time not adjusted when it should be. 2:years adjusted when it shouldn't be). Why could this be?
I will assume that the reason you want to roll it back by 5 hours is because of a timezone difference. If that's the case, you should use moment-timezone instead of moment.
With that said, subtracting 5 hours from the current date is actually simpler than what you're doing.
Before feeding a date into moment, you need to convert it to the js Date object like so: new Date('2021-01-10 00:00:00'). Since your parser function accepts the date in m/d H:M format, you would need to append the year to it first.
So here is how your code should look:
parser: function(utcMoment) {
const new_date = utcMoment.split(' ')[0] + '/' + (new Date().getFullYear()) + ' ' + utcMoment.split(' ')[1];
return moment(new Date(new_date)).subtract({hours: 5})
}

Convert date format to character string

I have a column of format DATETIME23. like this:
14.02.2017 13:00:25
I want to conver it to a string, so later, i would be able to modern it, so, for example, the final version would look like:
2017-02-14 13:00:25.000
Problem occures, when i try to convert date to char format: in result i have a string of smth like 1802700293 - which is the number of seconds.
I tried:
format date $23.0
or
date = put(date, $23.0)
P.S This is nother try:
data a;
format d date9.;
d = '12jan2016'd;
dtms = cat(day(d),'-',month(d),'-',year(d),' 00:00:00.000');
/* если нужно обязательно двухзначные день и месяц, то такой колхоз: */
if day(d) < 10 then dd=cat('0',put(day(d),$1.));
else ddday=put(day(d),$2.);
if month(d) < 10 then mm=cat('0',put(month(d),$1.));
else mm=put(month(d),$2.);
yyyy=put(year(d),$4.);
/*dtms2 = cat(dd,'-',mm,'-',yyyy,' 00:00:00.000');*/
dtms2 = cat(dd,'-',mm,'-',yyyy,' 00:00:00.000');
dtms = cat(day(d),'-',month(d),'-',year(d),' 00:00:00.000');
run;
BUT, abnormally, the dtms2 concat destroys the zero in the month element
If your datetime is stored as a SAS datetime, just use the appropriate format :
data test ;
dt = '09feb2017:13:53:26'dt ; /* specify a datetime constant */
new_dt = put(dt,E8601DT23.3) ; /* ISO datetime format */
run ;
Output
dt new_dt
1802267606 2017-02-09T13:53:26.000
If you need to replace the 'T' with a space, simply add a translate function around the put().
For your dtms solution you can use put and the Z2. format to keep the leading zero when you concatenate:
dtms = cat(day(d),'-', put(month(d),z2.),'-',year(d),' 00:00:00.000');
You should be able to just use put(date, datetime23.) for your problem though instead of $23, which is converting the number of seconds to a string with length 23. However, as a comment has mentioned datetime23. is not the format from your example.

New to python - trying to chose individual columns from transposed matrix

So presently code is as so:
table = []
for line in open("harrytest.csv") as f:
data = line.split(",")
table.append(data)
transposed = [[table[j][i] for j in range(len(table))] for i in range(len(table[0]))]
openings = transposed[1][1: - 1]
openings = [float(i) for i in openings]
mean = sum(openings)/len(openings)
print mean
minimum = min(openings)
print minimum
maximum = max(openings)
print maximum
range1 = maximum - minimum
print range1
This only prints one column of 7 for me, it also leaves out the bottom line. We are not allowed to import with csv module, use numpy, pandas. The only module allowed is os, sys, math & datetime.
How do I write the code so as to get median, first, last values for any column.
Change this line:
openings = transposed[1][1: - 1]
to this
openings = transposed[1][1:]
and the last row should appear. You calculations for mean, min, max and range seem correct.
For median you have to sort the row and select the one middle element or average of the two middle elements. First and last element is just row[0] and row[-1].

overuse of lists and string formating

This works, but is very un-Pythonic. I am sure I am overusing string formatting and lists. Can BeautifulSoup do it native?
from bs4 import BeautifulSoup
xmlurl = "http://forecast.weather.gov/MapClick.php?lat=33.37110&lon=-104.529&unit=0&lg=english&FcstType=dwml"
def get_forecast():
soup = BeautifulSoup(urllib2.urlopen(xmlurl))
temps = soup.find_all("temperature")
maxtemps = str(temps[0])
maxlist = maxtemps.split('\n')
maxvalue= str(maxlist[2]).lstrip()
maxvalue = maxvalue.replace('<value>','')
maxvalue = maxvalue.replace('</value>','')
mintemps = str(temps[1])
minlist = mintemps.split('\n')
minvalue= str(minlist[2]).lstrip()
minvalue = minvalue.replace('<value>','')
minvalue = minvalue.replace('</value>','')
print maxvalue
print minvalue
if __name__ == '__main__':
get_forecast()
temps comes back as a addressable as a list:
[<temperature time-layout="k-p24h-n7-1" type="maximum" units="Fahrenheit">
<name>Daily Maximum Temperature</name>
<value>65</value>
<value>75</value>
<value>88</value>
<value>92</value>
<value>92</value>
<value>89</value>
<value>83</value>
</temperature>, <temperature time-layout="k-p24h-n6-2" type="minimum" units="Fahrenheit">
<name>Daily Minimum Temperature</name>
<value>38</value>
<value>47</value>
<value>53</value>
<value>55</value>
<value>56</value>
<value>56</value>
</temperature>, <temperature time-layout="k-p1h-n1-1" type="apparent" units="Fahrenheit"> <value>53</value> </temperature>]
I then proceed to manipulate it (poorly) until I beat it into submission....
I have read through so many pages of documentation on Python and BeautifulSoup that I can't see straight. I'm sure BS4 can probably do this, but I haven't messed with XML enough to get the syntax right.
All I want is the first Daily Maximum Temperature (65) and the first Minimum Temperature (38).
Rather than overusing, I believe you are overthinking your approach. See the following code:
Code:
from bs4 import BeautifulSoup as bsoup
xml = """[<temperature time-layout="k-p24h-n7-1" type="maximum" units="Fahrenheit">
<name>Daily Maximum Temperature</name>
<value>65</value>
<value>75</value>
<value>88</value>
<value>92</value>
<value>92</value>
<value>89</value>
<value>83</value>
</temperature>, <temperature time-layout="k-p24h-n6-2" type="minimum" units="Fahrenheit">
<name>Daily Minimum Temperature</name>
<value>38</value>
<value>47</value>
<value>53</value>
<value>55</value>
<value>56</value>
<value>56</value>
</temperature>, <temperature time-layout="k-p1h-n1-1" type="apparent" units="Fahrenheit"> <value>53</value> </temperature>]"""
soup = bsoup(xml)
temps = soup.find_all("temperature")
max_temp = temps[0].find_all("value")[0].get_text()
print "Max temp: ", max_temp
min_temp = temps[1].find_all("value")[0].get_text()
print "Min temp: ", min_temp
Result:
Max temp: 65
Min temp: 38
[Finished in 0.6s]
You said you just want the first min and max temperatures, right? The way we did it is we create a soup first. Next, we search the soup for the temperature tags. We find two, one for the maximum and one for the minimum.
The third step -- finding the first of each -- is identical. First, we get the first temperature tag by using temps[0]. We then find all the elements with the value tag. The first element is returned by the [0] index. get_text() is just to get the inner text of the element. To get the first minimum temperature, we just change temps[0] to temps[1] so we can access the second temperature tag.
Let us know if this helps.