[Python]初心者筆記17(將date變數轉成格式化的字串,將date變數做"年" or "月" or "日" 的加減,string.index,string.indexof,string.find,substring in string)
將date變數轉成格式化的字串,將date變數做"年" or "月" or "日" 的加減:
#取得日期參數
import pandas as pd
#保留變數種類為Date
beginDt = pd.datetime.now().date()
#strftime轉成字串型態
beginDt = pd.datetime.now().date().strftime('%Y %m %d').replace(' ','%2F')
endDt = pd.datetime.now().date() + pd.DateOffset(months=6)
print (pd.datetime.now())
print (pd.datetime.now().date())
print (pd.datetime.now().year)
print (pd.datetime.now().month)
print (pd.datetime.now().day)
print (pd.datetime.now().hour)
print (pd.datetime.now().minute)
print (pd.datetime.now().second)
print (pd.datetime.now().microsecond)
string.index,string.indexof,string.find,substring in string:
#這是string.indexof,string.index
print('----------這是要找substring的position的情況-------------')
str1 = "this is string example....wow!!!";
str2 = "exam";
print('透過str.index(),發現str2在str1的位置是:' + str(str1.index(str2)))
print('當str.index()找不到substring的時候,會出現exception')
print('----------這是要找substring的position的情況--------------------------')
if str1.find(str2) > -1:
print('透過str.find()已確認str2的確存在於str1裡面!')
print('但是str.find()最好還是用來取得substring的position就好')
print('str2在str1的位置是' + str(str1.find(str2)))
print('-----------這是確認substring是否存在於原本string的情況-------------------------')
if str2 in str1:
print('透過 substring in string的語法,已確認str2存在於str1裡面')
參考資料:
Why does Python throw an error when a substring is not found?
https://stackoverflow.com/questions/25916842/why-does-python-throw-an-error-when-a-substring-is-not-found
How to change the datetime format in pandas
https://stackoverflow.com/questions/38067704/how-to-change-the-datetime-format-in-pandas
Add months to a date in Pandas
https://stackoverflow.com/questions/46741423/add-months-to-a-date-in-pandas