从字符串中提取指定日期和时间(Python)(初学者)

从一个用户输入了日期与时间,想要提取出来,以此获得我们想要的时间。

首先得想到我们输入的年月日都会以什么分割,比如 "/" "." "-" ":"这四个对吧,或者说用户是"年""月""日",那么好,想法很美好,现实很残酷,那么用到split()函数了,试试看吧

main = input("请输入现在的具体时间与日期:") #输入
#开始眼花的split()函数
year = main.split("-")[0]    
month = main.split("-")[1]
day = main.split("-")[2].split(" ")[0]
hour = main.split("-")[2].split(" ")[1].split(":")[0]
minute = main.split("-")[2].split(" ")[1].split(":")[1]
second = main.split("-")[2].split(" ")[1].split(":")[2]
#看查用户输入的和自己想要的
print(main)
print(year, month, day, hour, minute, second)

是不是感觉到非常的复杂,比如?在外行人看着高级的函数————

pandas.Series.dt.year——pandas.Series.dt.month

pandas.DatetimeIndex.year——pandas.DatetimeIndex.month

strftime()

print("从这里开始为代码搬运,代码出处来自 @条件漫步 大佬")

对于pandas.Series.dt.year——pandas.Series.dt.month的使用

import pandas as pd

list_of_dates = ['2019-11-20', '2020-01-02', '2020-02-05','2020-03-10','2020-04-16']
employees=['Hisila', 'Shristi','Zeppy','Alina','Jerry']
df = pd.DataFrame({'Joined date': pd.to_datetime(list_of_dates)}, index=employees)

df['Year'] = df['Joined date'].dt.year
df['Month'] = df['Joined date'].dt.month
df['Day'] = df['Joined date'].dt.day
# 转化为日期类型datetime64[ns]
df['Date'] = pd.to_datetime(df['Joined date'].dt.date)
print(df)

#https://blog.csdn.net/chenhepg/article/details/118799729代码出处

对于pandas.DatetimeIndex.year——pandas.DatetimeIndex.month的使用

import pandas as pd

list_of_dates = ['2019-11-20', '2020-01-02', '2020-02-05','2020-03-10','2020-04-16']
employees=['Hisila', 'Shristi','Zeppy','Alina','Jerry']
df = pd.DataFrame({'Joined date': pd.to_datetime(list_of_dates)},index=employees)

df['year'] = pd.DatetimeIndex(df['Joined date']).year
df['month'] = pd.DatetimeIndex(df['Joined date']).month

print(df)

#https://blog.csdn.net/chenhepg/article/details/118799729代码出处

对于strftime()函数表达

import pandas as pd

list_of_dates = ['2019-11-20', '2020-01-02', '2020-02-05','2020-03-10','2020-04-16']
employees=['Hisila', 'Shristi','Zeppy','Alina','Jerry']
df = pd.DataFrame({'Joined date': pd.to_datetime(list_of_dates)},index=employees)

df['year'] = df['Joined date'].dt.strftime('%Y')
df['month'] = df['Joined date'].dt.strftime('%m')

#https://blog.csdn.net/chenhepg/article/details/118799729的代码出处
print("搬运结束,开始原创")

想一想如果有一个东西,会不会一步到位呢?比如《正则表达式》,诶嘿!

所以,经过我被班主任的洗礼我以头发掉光的代价理解了正则表达式,代码如下

# 2023年3月24日 10:00:00
"(\d{4}-\d{1,2}-\d{1,2} \d{1,2}:\d{1,2}:\d{1,2})"
# 2023年3月24日 10:00
"(\d{4}-\d{1,2}-\d{1,2})"
# 2023年3月24日
"(\d{4}-\d{1,2}-\d{1,2})"
# 2023年3月
"(\d{4}-\d{1,2})"

#有具体到秒,具体到分,具体到日,具体到月

诶......怎么就这么简单呢,封装完后:

def get_strtime(text):
	text = text.replace("年", "-").replace("月", "-").replace("日", " ").replace("/", "-").strip()
	text = re.sub("\s+", " ", text)
	t = ""
	regex_list = [
		# 2013年8月15日 22:46:21
        "(\d{4}-\d{1,2}-\d{1,2} \d{1,2}:\d{1,2}:\d{1,2})",
        # "2013年8月15日 22:46"
        "(\d{4}-\d{1,2}-\d{1,2} \d{1,2}:\d{1,2})",
        # "2014年5月11日"
        "(\d{4}-\d{1,2}-\d{1,2})",
        # "2014年5月"
        "(\d{4}-\d{1,2})",
	]
	for regex in regex_list:
		t =  re.search(regex, text)
		if t:
			t = t.group(1)
			return t
	else:
		print("没有获取到有效日期")
	
	return t

#已经有大佬分享出来了~想的基本一样,代码来自https://blog.csdn.net/weixin_43886133/article/details/102763892

正则可以通过自己的理解进行独自创作 初学者可以看一看拉~

例如:[1-9] \d {0,3} 这代表了什么呢? [1-9]代表了第一位数例如1840年,我的年份第一位数 “1”,\d表示了我年份第二位开始能有吧(可有可无)。但是在我们的认知,我们的年份最大4位数(9999),{0,3}代表什么呢?比如1840年“1”我判断完了是[1-9],还剩下"840"三位,这三位可以没有{0,}也可以3位全有{0, 3}。

详细的字符用法可以回到我的主页

r'^[1-9]\d{0,3}[-.\/:](0?[1-9]|1[0-2])[-.\/:](0?[1-9|[12]\d|3[01])$'

正则表达式元字符和语法(Python)(初学者)_GHK_Bi_Lian的博客-CSDN博客有详细介绍

我们使用了三种方法来获得我们所要的时间日期,每一个都能用,也有各自的优点

希望看到我文章的初学者,不是Ctrl C+Ctrl V 而是理解代码的逻辑,能够编写自己的程序

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值