Change panda date format into another date format? - python-3.x

How do I convert this format below into the result format ?
import pandas as pd
date = pd.date_range('2022-01-01',2022-01-31', freq = 'H')
Result:
'2021-01-01T01%3A00%3A00',
What is the correct name for the result time format ? Have tried using urlilib.parse module, but it did not have T and it can take 1 date.
Thank you !

This so called url encode , so we need urllib, notice here %3A = ':'
import urllib
date.astype(str).map(urllib.parse.quote)
Out[158]:
Index(['2022-01-01%2000%3A00%3A00', '2022-01-01%2001%3A00%3A00',
....

Related

How to strip a string from a datetime stamp?

I am reading the attached excel file (only an image attached) using Pandas. There is one row with DateTime stamp with following format (M- 05.02.2018 13:41:51). I would like to separate/remove the 'M-' from DateTime in the whole row.
import pandas as pd
df=pd.read_excel('test.xlsx')
df=df.drop([0,1,2,3])
I would then like to use the following code to convert to Datetime:
df.iloc[0]= pd.to_datetime(df.iloc[0], format='%d.%m.%Y %H:%M:%S')
Can please someone help me to remove the 'M-' from the complete row?
Thank you.
Excel-file (image)
Use pandas.Series.str.strip to remove 'M-' from the rows:
If removing from the rows:
df['Column_Name'] = df['Column_Name'].str.strip('M- ')
If removing from columns or DataFrame headers:
df.columns = df.columns.str.strip('M- ')
You may want Series.str.lstrip to remove leading characters from row.
df.iloc[0] = df.iloc[0].str.lstrip('M- ')

python3 formatting SQL response from rows to string

im trying to print values from database and im getting this output:
[('CPDK0NHYX9JUSZUYASRVFNOMKH',), ('CPDK0KUEQULOAYXHSGUEZQGNFK',), ('CPDK0MOBWIG0T5Z76BUVXU5Y5N',), ('CPDK0FZE3LDHXEJRREMR0QZ0MH',)]
but will like to have this fromat:
'CPDK0NHYX9JUSZUYASRVFNOMKH'|'CPDK0KUEQULOAYXHSGUEZQGNFK'|'CPDK0MOBWIG0T5Z76BUVXU5Y5N'|'CPDK0FZE3LDHXEJRREMR0QZ0MH'
Python3
existing code
from coinpayments import CoinPaymentsAPI
from datetime import datetime
from lib.connect import *
import argparse
import json
sql = 'SELECT txn_id FROM coinpayment_transactions WHERE status = 0 '
mycursor.execute(sql)
result = mycursor.fetchall()
mydb.close()
print(result)
What you are getting is a list of tuples and it is stored in result object. If you want the output to be formatted the way you say then do this
#Paste this instead of print(result)
output=''
for i in result:
if (output!=''):
output=output+'|'+"'"+i[0]+"'"
else:
output=output+"'"+i[0]+"'"
print(output)
The better way to do these kinds of thing is using join and format() methods of string.
Here is your solution:
output = '|'.join([f"'{row[0]}'" for row in result])
print(output)

How to insert todays date automatically?

I want to insert today's date in the following code automatically.
import shutil
shutil.copy(r"C:\Users\KUNDAN\Desktop\Backup\Cash MAR.2017 TO APR.2019.accdb",
r"F:\Cash MAR.2017 TO APR.2019 (11-09-19).accdb ")
print("DONE !!!")
First off, I'm not 100% sure of your question. If this doesn't answer it as you're expecting, please reformat your question to add clarity.
You can do this via the datetime library and string formatting. For example (using UK date format):
import shutil
from datetime import datetime as dt
today = dt.today().strftime('%d-%m-%y')
src = "C:/Users/KUNDAN/Desktop/Backup/Cash MAR.2017 TO APR.2019.accdb"
dst = "F:/Cash MAR.2017 TO APR.2019 ({today}).accdb".format(today=today)
shutil.copy(src, dst)
print("DONE !!!")
I have found these two links very useful:
string formatting
datetime formatting using strftime
import datetime
datetime_now = datetime.datetime.now()
print(datetime_now)
It will print the date and time for now and you can choose what format you like.

How to convert a/p (am/pm) time value in python to 24hr format

I am reading a csv file which has a time field as 3:50a and 4:25p. I need to convert this time values to 24 hour clock format as H:M for this I am doing:
datetime.strptime(str(time_value), '%I:%M').strftime('%H:%M')
where time_value is 3:50a or 4:25p. Now the problem is above line of code do not work because I have not inlucded the AM/PM tag which is %p in %I:%M and that is because in the csv file I am just getting a for AM and p for PM.
How can I deal with this situation. I need to convert the time_value to 24hr clock format. Thanks
Add an 'm' to the string you input to strptime and put the %p in its second argument,
>>> from datetime import datetime
>>> time_value = '3:50a'
>>> datetime.strptime(str(time_value)+'m', '%I:%M%p').strftime('%H:%M')
'03:50'
>>> time_value = '4:25p'
>>> datetime.strptime(str(time_value)+'m', '%I:%M%p').strftime('%H:%M')
'16:25'

date-time-string to UNIX time with milliseconds

I need to convert a date/time string to UNIX timestamp including the milliseconds. As the timetuple() does not include milli or microseconds I made a short workaround. But I was wondering, is there a better/nicer way to do this?
import datetime as dt
import time
timestamp = '2018-01-19 10:00:00.019' # example of input time string
tmp = timestamp.split('.')
millisec = tmp[-1] # extracting only milli-seconds
UX_time = time.mktime(dt.datetime.strptime(tmp[0], '%Y-%m-%d %H:%M:%S').timetuple()) + float(millisec)/1e3
print(UX_time)
1516352400.019
I realize my timezone is off by one hour, so you might be getting
print(UX_time)
1516356000.019
you can try this:
timestamp = '2018-01-19 10:00:00.019'
tmp=np.datetime64(timestamp)
print(tmp.view('<i8')/1e3)
output:
1516352400.019
Also possible with your current code:
import datetime as dt
import time
timestamp = '2018-01-19 10:00:00.019' # example of input time string
ts = dt.datetime.strptime(timestamp, '%Y-%m-%d %H:%M:%S.%f')
UX_time = time.mktime(ts.timetuple()) + ts.microsecond/1e6
print "%.3f" %UX_time

Resources