简体   繁体   English

Python - 希望使用切片删除剩余的字符串

[英]Python - Looking to remove remaining string using slice

Looking to remove the rest of a date input in the folllowing format: 2018-10-03 11:46:00.希望删除以下格式的日期输入的 rest:2018-10-03 11:46:00。 I want to remove the time portion.我想删除时间部分。 So far my code reads:到目前为止,我的代码如下:

out1.due_date = out1.due_date[10:]

I am using a program called Data 360, and the out1 is what is used to process the records.我正在使用一个名为 Data 360 的程序,out1 用于处理记录。 However, I am a bit puzzled on how I could remove everything after the yyyy-mm-dd input.但是,我对如何在 yyyy-mm-dd 输入后删除所有内容感到有些困惑。

Thanks!谢谢!

Use split function to achieve this, the method splits a string into a list.You can specify the separator, default separator is a whitespace.使用 split function 来实现这一点,该方法将一个字符串拆分为一个列表。您可以指定分隔符,默认分隔符是空格。 So out1.due_date.split() would return list ['2018-10-03','11:46:00'].所以 out1.due_date.split() 将返回列表 ['2018-10-03','11:46:00']。 Since interested in date, use zero as the index.由于对日期感兴趣,因此使用零作为索引。

out1.due_date= out1.due_date.split()[0]  

Using fromisoformat to parse the string to a datetime object and extracting date part out of it, by calling date() on it.使用fromisoformat将字符串解析为日期时间 object 并通过调用date()从中提取日期部分。

from datetime import date, datetime

print(datetime.fromisoformat(out1.due_date).date())

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM