Change time from 12-h to 24-h format - python

I want to convert a time from 12-h format to 24-h format
This is my code:
def change_time(time):
import datetime as dt
FMT12 = '%H:%M:%S %p'
FMT24 = '%H:%M:%S'
# time is a string
if time.find('PM') != -1: # if exists
t1 = dt.datetime.strptime(time, FMT12)
t2 = dt.datetime.strptime('12:00:00', FMT24)
time_zero = dt.datetime.strptime('00:00:00', FMT24)
return (t1 - time_zero + t2).time()
else:
return dt.datetime.strptime(time, FMT12).time()
This is the output :
print(change_time('09:52:08 PM')) # -> 21:52:08
So, this code is working, but I want a better version of it.

Here is a much faster working method:
from datetime import datetime
def change_time(time):
in_time = datetime.strptime(time, "%I:%M:%S %p")
new_time = datetime.strftime(in_time, "%H:%M:%S")
print(new_time)
change_time('09:52:08 PM')
Output:
>>> 21:52:08

def t12_to_24(time):
am_or_pm = time[-2] + time[-1]
time_update = ''
if am_or_pm == 'am' or am_or_pm == 'AM':
for i in time[0:-3]:
time_update += i
elif am_or_pm == 'pm' or am_or_pm == 'PM':
change = ''
for i in time[0:2]:
change += i
c = 12 + int(change)
if c >= 24:
c = 24 - c
c = list(str(c))
for i1 in c:
time_update += i1
for i2 in time[2:-3]:
time_update += i2
print(time_update)
time = list(input())
t12_to_24(time)

Related

Replacing a character in a string but it duplicate

This is a line of code I create that will replace a '_' with a character from a string
def test():
time = -1
in_time = 0
n = 'c__rd_nate'
new_n = ''
word = 'coordinate'
chr = 'i'
for w in word:
time = time + 1
if w == chr:
for i in n:
if in_time == time:
u = i.replace(i, chr)
new_n = new_n + u
in_time = in_time + 1
else:
in_time = in_time + 1
new_n = new_n + i
if len(word) == in_time:
break
Output:
>>>c__rdinate
But when applying the same rules for the duplicate character 'o' in word
def test():
time = -1
in_time = 0
n = 'c__rd_nate'
new_n = ''
word = 'coordinate'
chr = 'o'
for w in word:
time = time + 1
if w == chr:
for i in n:
if in_time == time:
u = i.replace(i, chr)
new_n = new_n + u
in_time = in_time + 1
else:
in_time = in_time + 1
new_n = new_n + i
if len(word) == in_time:
break
Output:
>>>co_rd_natec__rd_nate
I know what the error is but I'm stuck at creating a solution for this type of problem!
This is some more output in the same situation!
def test():
time = -1
in_time = 0
n = 'd__r'
new_n = ''
word = 'door'
chr = 'o'
for w in word:
time = time + 1
if w == chr:
for i in n:
if in_time == time:
u = i.replace(i, chr)
new_n = new_n + u
in_time = in_time + 1
else:
in_time = in_time + 1
new_n = new_n + i
if len(word) == in_time:
break
print(new_n)
test()
Output:
>>>do_rd__r
Converting the string to a list and then performing item assingment would be much more convenient.
This is a much more simplified way of constructing the code:
def test():
count = 0
n = list('c__rd_nate')
word = 'coordinate'
chr = 'o'
for w in word:
if w == chr:
n[count] = chr
count += 1
print(''.join(n))
output:
coord_nate
Edit:
If you would prefer to still keep the variable new_n then you can do something like this:
def test():
count = 0
n = list('c__rd_nate')
new_n = ''
word = 'coordinate'
chr = 'o'
for w in word:
if w == chr:
n[count] = chr
new_n = new_n + n[count]
count += 1
print(new_n)
output:
coord_nate
I think, you don't have to complicate too much. If you used indexing, problem can be solved with ease. If pattern matches, then concatenate that letter from variable "word" else concatenate from variable "n"
n = 'c__rd_nate'
new_n = ''
word = 'coordinate'
chr = 'o'
for i in range(len(word)):
if word[i] == chr:
new_n += word[i]
else:
new_n += n[i]
print(new_n)
This works for both 'o' and 'i'.
Output for 'o'
coord_nate
Output for 'i'
c__rdinate
def test():
n = 'doorian'
word = 'd__r_an'
ch = 'o'
return ''.join(_l if _l == '_' and word_l == ch else word_l
for word_l, _l in zip(word, n))
Or in cycle
def test():
n = 'doorian'
word = 'd__r_an'
ch = 'o'
res = ''
for word_l, _l in zip(word, n):
if _l == '_' and word_l == ch:
res += _l
else:
res += word_l
return res

Can anyone give me a function to calculate date and time in python ? I m in WINDOWS 10

Please can anyone provide me function for time,date & day in python
just like time = time()
and time = "##:##:##" # is replaced with current time in my laptop
And date = date()
and date = "####/##/##"
And day = day()
and day = "sun/mon/tue/wed/etc"
import subprocess as sp
import datetime as dt
def time():
t = dt.datetime.now()
h = str(int(t.strftime("%H")))
m = str(int(t.strftime("%M")))
s = str(int(t.strftime("%S")))
ampm = " AM "
h = int(h)
if h > 12:
h = h - 12
ampm = " PM "
h =str(h)
return str(h) + ":" + t.strftime("%M:%S") + " " + ampm
def out(command,he):
result = he.run(command, stdout=he.PIPE, stderr=he.PIPE, universal_newlines=False, shell=True)
d = result.stdout
outp = d
f = d.find(b'\r')
if f>0:
outp = d[0:f]
outp = str(outp)
outp = outp[2:len(outp)-1]
return outp
def date(han):
myot = out("echo %date%",han)
myot = myot[4:len(myot)]
return myot
def day(he):
myot = out("echo %date%",he)
myot = myot[0:3]
if myot == "Wed":
myot = myot + "nes"
elif myot == "Thu":
myot = myot + "rs"
elif myot == "Sat":
myot = myot + "ur"
elif myot == "Tue":
myot = myot + "s"
myot = myot + "day"
return myot
date = date(sp)
day = day(sp)
time = time()
To get a timestamp with the current time and date you can use:
import datetime
timestamp = datetime.datetime.now()
You can then use that timestamp object to get the information you need with:
timestamp.year
timestamp.month
timestamp.day
timestamp.hour
timestamp.minute
timestamp.second
timestamp.weekday() - This is a method and so you need the parenthesis
If you want to understand a bit more what you are doing you can read the python datetime documentation https://docs.python.org/3/library/datetime.html

Python returns ints when one of variable inside function is active

The main idea is:
searchindex() - repeat binary search algorithm over the list of random data with looking back and with fix.(variable counter1 should save number of occurences)
occur() - just assumning total number of occurences.
Please help to find a problem.
I always get counter1 = 0 after running a code.
def searchindex(searchlist, secs, x):
ts = calendar.timegm(time.gmtime())
delta_minute_ts = (ts - (ts % 60)) - secs
last_minute = datetime.datetime.fromtimestamp(delta_minute_ts).strftime('%Y-%m-%d %H:%M')
start = 0
end = len(searchlist) - 1
counter1 = 0
while (start <= end):
mid = (start + end) // 2
if (searchlist[mid] == last_minute):
counter1 = int(mid)
if x == 1:
end = mid - 1
else:
start = mid + 1
elif (last_minute < searchlist[mid]):
end = mid - 1
else:
start = mid + 1
return counter1
def occur():
start_result = searchindex(new1, 60, 1)
end_result = searchindex(new1, 60, 2)
if start_result is None:
return 'no results'
else:
end_result - start_result + 1

How to put numbers in a time format if conversions are already completed?

I am trying to take a string and convert into 24 hour time. For example, if I am given the string "07:05:45PM", it should return "19:05:45". I have completed all the necessary conversions, I am just not sure how I am supposed to put them all together and have it so that if there were only 5 minutes or 5 seconds, it would place a zero like "xx:05:06".
def timeConversion(s):
nums = s[:8]
hh,mm,ss = [v for v in nums.split(":")]
time = s[8:]
if time == 'AM':
return nums
else:
total = (int(hh) * 3600 + int(mm) * 60 + int(ss)) + 43200
if s == "12:00:00PM":
return nums
hh = total // 3600
mm = total // 60 % 60
ss = total % 60
print(timeConversion("07:05:45PM"))
Only the hours and suffix have any significance in your output. The key is that 12AM is 00, and 12PM is 12. 12:00 is not the only time that deserves this treatment: 12:01 does too. Use the modulo operator to avoid any special cases at all:
def time_conversion(s):
hh = int(s[:2]) % 12 # this is the magical part 12->0
mmss = s[2:8]
suffix = s[8:].strip().upper()
if suffix == 'PM':
hh += 12
return f'{hh:02d}{mmss}'
Here is the working code. For the input "07:05:45PM", it returns "19:05:45". You just need to add a '0' if the minutes or seconds values are less than 10.
def timeConversion(s):
nums = s[:8]
hh,mm,ss = [v for v in nums.split(":")]
time = s[8:]
if time == 'AM':
return nums
else:
total = (int(hh) * 3600+int(mm)*60+int(ss))+43200
if s == "12:00:00PM":
return nums
hh = str(total//3600)
mm = total//60 % 60
ss = total % 60
mm_str = '0'+ str(mm) if mm <= 9 else str(mm)
ss_str = '0'+ str(ss) if ss <= 9 else str(ss)
time_str = str(hh) + ':' + mm_str + ":" + ss_str
return time_str
print(timeConversion("07:05:45PM"))
Since you are dealing with a string, perhaps most of the code could deal with the string.
EDIT: Revised code as per Mad Physicist's comments
def convert(s):
if s[8:] == 'AM':
if s[:2] == '12':
return '00' + s[2:8]
else:
return s[:8]
elif s[8:] == 'PM':
if s[:2] == '12':
return s[:8]
else:
return str(int(s[:2])+ 12) + s[2:8]
for t in ['12:00:00AM', '01:01:01AM', '12:01:01PM', '01:10:11PM', '11:20:20PM']:
print(t, convert(t))
Prints:
12:00:00AM 00:00:00
01:01:01AM 01:01:01
12:01:01PM 12:01:01
01:10:11PM 13:10:11
11:20:20PM 23:20:20

String Slicing in python UDF

I am trying to write a UDF in python that will be called from a pig script. The UDF needs to accept the date as a string in DD-MMM-YYYY format and return DD-MM-YYYY format. Here MMM will be like JAN, FEB.. DEC and the return MM will be 01, 02... 12.
Below is my python UDF
#!/usr/bin/python
#outputSchema("newdate:chararray")
def GetMonthMM(inputString):
print inputString
#monthstring = inputString[3:6]
sl = slice(3,6)
monthstring = inputString[sl]
monthdigit = ""
if ( monthstring == "JAN" ):
monthdigit = "01"
elif ( monthstring == "FEB"):
monthdigit = "02"
elif(monthstring == "MAR"):
monthdigit = "03"
elif(monthstring == "APR"):
monthdigit = "04"
elif(monthstring == "MAY"):
monthdigit = "05"
elif (monthstring == "JUN"):
monthdigit = "06"
elif (monthstring == "JUL"):
monthdigit = "07"
elif (monthstring == "AUG"):
monthdigit = "08"
elif (monthstring == "SEP"):
monthdigit = "09"
elif (monthstring == "OCT"):
monthdigit = "10"
elif (monthstring == "NOV"):
monthdigit = "11"
elif (monthstring == "DEC"):
monthdigit = "12"
sl1 = slice(0,3)
sl2 = slice(6,11)
str1 = inputString[sl1]
str2 = inputString[sl2]
newdate = str1 + monthdigit + str2
return monthstring;
I did some debugging and the issue seems to be that after the slicing the strings are being treated as arrays. I get the following error message
TypeError: unsupported operand type(s) for +: 'array.array' and 'str'
The same is happening even when the string is being compared to another string like at if (monthstring == "DEC"):.
Even when monthstring has DEC as value the condition never satisfies.
Has anybody faced the same issue before? Any ideas how to fix this.
Recently I've used the calendar module, might be more useful in different cases, but anyway.
import calendar
m_dict = {}
for i, month in enumerate(calendar.month_abbr[1:]): #for some reason month_abbr[0] = '', so ommit that
m_dict[month.lower()] = '{:02}'.format(i+1)
def GetMonthMM(inputStr):
day, month, year = inputStr.split('-')
return '-'.join([day, m_dict[month.lower()], year])
print(GetMonthMM('01-JAN-2015'))
# prints 01-01-2015
I would write this function as this:
#!/usr/bin/python
#outputSchema("newdate:chararray")
def GetMonthMM(inputString):
monthArray = {'JAN':'01','FEB':'02','MAR':'03','APR':'04','MAY':'05','JUN':'06','JUL':'07','AUG':'08','SEP':'09','OCT':'10','NOV':'11','DEC':'12'}
print inputString
#monthstring = inputString[3:6]
dateparts = string.join(inputString).split('-') #assuming the date is always separated by -
dateparts[1] = monthArray[dateparts[1]]
return dateparts.join('-');

Categories