如何将以下字符串转换为datetime对象?
"Jun 1 2005 1:33PM"
如何将以下字符串转换为datetime对象?
"Jun 1 2005 1:33PM"
当前回答
将yyyy-mm-dd日期字符串映射到datetime.date对象的简短示例:
from datetime import date
date_from_yyyy_mm_dd = lambda δ : date(*[int(_) for _ in δ.split('-')])
date_object = date_from_yyyy_mm_dd('2021-02-15')
其他回答
如果您的字符串是ISO 8601格式,并且您有Python 3.7+,则可以使用以下简单代码:
import datetime
aDate = datetime.date.fromisoformat('2020-10-04')
日期和
import datetime
aDateTime = datetime.datetime.fromisoformat('2020-10-04 22:47:00')
用于包含日期和时间的字符串。如果包含时间戳,函数datetime.datetime.isoformat()支持以下格式:
YYYY-MM-DD[*HH[:MM[:SS[.fff[fff]]]][+HH:MM[:SS[.ffffff]]]]
其中*匹配任何单个字符。另请参见此处和此处。
这里没有提到但很有用的一点:在当天添加后缀。我解耦了后缀逻辑,这样你就可以将它用于任何你喜欢的数字,而不仅仅是日期。
import time
def num_suffix(n):
'''
Returns the suffix for any given int
'''
suf = ('th','st', 'nd', 'rd')
n = abs(n) # wise guy
tens = int(str(n)[-2:])
units = n % 10
if tens > 10 and tens < 20:
return suf[0] # teens with 'th'
elif units <= 3:
return suf[units]
else:
return suf[0] # 'th'
def day_suffix(t):
'''
Returns the suffix of the given struct_time day
'''
return num_suffix(t.tm_mday)
# Examples
print num_suffix(123)
print num_suffix(3431)
print num_suffix(1234)
print ''
print day_suffix(time.strptime("1 Dec 00", "%d %b %y"))
print day_suffix(time.strptime("2 Nov 01", "%d %b %y"))
print day_suffix(time.strptime("3 Oct 02", "%d %b %y"))
print day_suffix(time.strptime("4 Sep 03", "%d %b %y"))
print day_suffix(time.strptime("13 Nov 90", "%d %b %y"))
print day_suffix(time.strptime("14 Oct 10", "%d %b %y"))
Use:
emp = pd.read_csv("C:\\py\\programs\\pandas_2\\pandas\\employees.csv")
emp.info()
它显示“开始日期时间”列和“上次登录时间”都是数据帧中的“对象=字符串”:
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 1000 entries, 0 to 999
Data columns (total 8 columns):
First Name 933 non-null object
Gender 855 non-null object
Start Date 1000 non-null object
Last Login Time 1000 non-null object
Salary 1000 non-null int64
Bonus % 1000 non-null float64
Senior Management 933 non-null object
Team 957 non-null object
dtypes: float64(1), int64(1), object(6)
memory usage: 62.6+ KB
通过使用read_csv中的parse_dates选项,可以将字符串datetime转换为panda datetime格式。
emp = pd.read_csv("C:\\py\\programs\\pandas_2\\pandas\\employees.csv", parse_dates=["Start Date", "Last Login Time"])
emp.info()
输出:
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 1000 entries, 0 to 999
Data columns (total 8 columns):
First Name 933 non-null object
Gender 855 non-null object
Start Date 1000 non-null datetime64[ns]
Last Login Time 1000 non-null datetime64[ns]
Salary 1000 non-null int64
Bonus % 1000 non-null float64
Senior Management 933 non-null object
Team 957 non-null object
dtypes: datetime64[ns](2), float64(1), int64(1), object(4)
memory usage: 62.6+ KB
#Convert String to datetime
>>> x=datetime.strptime('Jun 1 2005', '%b %d %Y').date()
>>> print(x,type(x))
2005-06-01 00:00:00 <class 'datetime.datetime'>
#Convert datetime to String (Reverse above process)
>>> y=x.strftime('%b %d %Y')
>>> print(y,type(y))
Jun 01 2005 <class 'str'>
您可以使用easy_date简化操作:
import date_converter
converted_date = date_converter.string_to_datetime('Jun 1 2005 1:33PM', '%b %d %Y %I:%M%p')