[Python]初心者笔记17(将date变量转成格式化的字符串,将date变量做”年”  or “月” or “日”  的加减,string.index,string.indexof,string.find,substring in string)

[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