在Python中,时间是一个经常被使用的对象。在很多情况下,我们需要根据特定的格式将时间字符串转换为日期时间对象。 Python中的datetime.strptime()方法就可以帮助我们完成这一转换工作。本文将详细介绍datetime.strptime()方法的使用。
一、strptime()方法介绍
datetime.strptime(date_string, format)是Python中用于将字符串日期时间转换成日期时间对象的方法。其中,date_string是需要转换的字符串,format是字符串的时间格式.
from datetime import datetime
date_string = "2021-06-01 08:30"
format = "%Y-%m-%d %H:%M"
datetime_object = datetime.strptime(date_string, format)
print(datetime_object)
执行以上代码后,我们会得到一个datetime对象:
2021-06-01 08:30:00
二、format格式说明
下面是一些常用的format格式说明。
| Directive | Meaning | Example |
|---|---|---|
| %Y | Year with century | 2021 |
| %m | Month as a zero-padded decimal number | 06 |
| %B | Month as locale’s full name | June |
| %d | Day of the month as a zero-padded decimal number | 01 |
| %j | Day of the year as a zero-padded decimal number | 152 |
| %U | Week number of the year (Sunday as the first day of the week) | 22 |
| %w | Weekday as a decimal number (0-6, Sunday is 0) | 1 |
| %H | Hour (24-hour clock) as a zero-padded decimal number | 08 |
| %M | Minute as a zero-padded decimal number | 30 |
| %S | Second as a zero-padded decimal number | 00 |
| %f | Microsecond as a decimal number, zero-padded on the left | 000000 |
三、实际应用案例
1、将时间字符串转换成Unix时间戳
from datetime import datetime
date_string = "2021-06-01 08:30"
format = "%Y-%m-%d %H:%M"
datetime_object = datetime.strptime(date_string, format)
timestamp = datetime_object.timestamp()
print(timestamp)
输出结果为:
1622526600.0
2、将不同格式的时间字符串统一转换成datetime对象
from datetime import datetime
date_string_list = ["2021-06-01 08:30", "2021/06/01/08/30", "2021|06|01 08:30"]
for date_string in date_string_list:
if "|" in date_string:
format = "%Y|%m|%d %H:%M"
elif "/" in date_string:
format = "%Y/%m/%d/%H/%M"
else:
format = "%Y-%m-%d %H:%M"
datetime_object = datetime.strptime(date_string, format)
print(datetime_object)
输出结果为:
2021-06-01 08:30:00
2021-06-01 08:30:00
2021-06-01 08:30:00
3、根据日期时间对象输出不同格式的字符串
from datetime import datetime
date_object = datetime(2021, 6, 1, 8, 30)
format1 = "%Y-%m-%d %H:%M"
format2 = "%Y/%m/%d %H:%M"
date_string1 = date_object.strftime(format1)
date_string2 = date_object.strftime(format2)
print(date_string1)
print(date_string2)
输出结果为:
2021-06-01 08:30
2021/06/01 08:30
四、总结
datetime.strptime()方法是Python中非常有用的一个日期时间处理方法,它可以帮助我们将字符串日期时间转换成日期时间对象,并且可以通过format参数自定义时间格式,非常灵活。在日常工作中,学会使用datetime.strptime()方法可以为我们的编程工作带来很多便利。
原创文章,作者:小蓝,如若转载,请注明出处:https://www.506064.com/n/207131.html
微信扫一扫
支付宝扫一扫