Python 如何将字符串转换为时间日期 datetime 格式?[手机环球网]

Python 如何将字符串转换为时间日期 datetime 格式?[手机环球网]

已邀请:
datetime.strptime() 按照给定的 datetime 格式来解析字符串,解析成功的话,返回 datetime 对象。

datetime.strptime() 举例
7-May-2013 格式
from datetime import datetime

dateString = "7-May-2018"
dateFormatter = "%u-%b-%Y"
datetime.strptime(dateString, dateFormatter)
输出:

datetime.datetime(2013, 5, 1, 0, 0)
31/12/2018 格式
from datetime import datetime

dateString = "31/12/2013"
dateFormatter = "%d/%m/%Y"
datetime.strptime(dateString, dateFormatter)
输出:

datetime.datetime(2013, 12, 31, 0, 0)
Mon, July 16 2018格式
from datetime import datetime

dateString = "31/12/2013"
dateFormatter = "%d/%m/%Y"
datetime.strptime(dateString, dateFormatter)
输出:

datetime.datetime(2018, 7, 16, 0, 0)
Monday, July 16, 2018 20:01:56 格式
from datetime import datetime

dateString = "Monday, July 16, 2018 20:01:56"
dateFormatter = "%A, %B %d, %Y %H:%M:%S"
datetime.strptime(dateString, dateFormatter)
输出:

datetime.datetime(2018, 7, 16, 20, 1, 56)

要回复问题请先登录注册