如何在python中将字符串日期(2021年1月25日)转换为y-m-d日期(2021-01-01)

时间:2021-01-26 01:09:21

标签: python datetime converters

我有像 pub fn ancestor_ids( &self, node_id: &NodeId ) -> Result<AncestorIds<T>, NodeIdError> pub fn move_node( &mut self, node_id: &NodeId, behavior: MoveBehavior ) -> Result<(), NodeIdError> (Jan,Feb,Mar,May,Jun,Jul,Aug,Sep,Oct,Nov,Dec) 这样的字符串,如何将其转换为 use id_tree::*; use id_tree::InsertBehavior::*; use id_tree::MoveBehavior::*; struct MyApp{ pub tree: Tree<i32> } fn main() { // 0 // / \ // 1 2 // / \ // 3 4 let mut my_app = MyApp{ tree: TreeBuilder::new().with_node_capacity(5).build() }; let root_id: NodeId = my_app.tree.insert(Node::new(0), AsRoot).unwrap(); let child_id: NodeId = my_app.tree.insert(Node::new(1), UnderNode(&root_id)).unwrap(); let node_2_id: NodeId = my_app.tree.insert(Node::new(2), UnderNode(&root_id)).unwrap(); let node_3_id: NodeId = my_app.tree.insert(Node::new(3), UnderNode(&child_id)).unwrap(); let node_4_id: NodeId = my_app.tree.insert(Node::new(4), UnderNode(&child_id)).unwrap(); // let the_rc = std::rc::Rc::new(my_app.tree); // let mut ancestor_ids = the_rc.ancestor_ids(&node_4_id).unwrap(); //Err: creating rc moves the value let mut ancestor_ids = my_app.tree.ancestor_ids(&node_4_id).unwrap(); //Err: creates a immutable borrow, which causes an error because move_node creates a mutable borrow //let mut ancestor_ids = my_app.tree.clone().ancestor_ids(&node_4_id).unwrap(); //Err: cannot clone my_app.tree becuase clone() generates a new tree with different NodeId Values, causing move_node to panic let tx = my_app.tree.move_node( &node_4_id, ToParent(ancestor_ids.next().unwrap()) ); }

我正在定义一个函数,如:

Jan 25, 2021

问题是月份词,所以也许我可以将字符串替换为月份数字,然后将其转换,但我卡住了

2 个答案:

答案 0 :(得分:5)

正如您在我的评论中看到的,您只需要使用正确的匹配掩码即可。

您的日期字符串采用 %b %d, %Y 格式,因此您需要在 strptime() 中使用相同的掩码。考虑到这一点,这样的函数就可以完成这项工作:

from datetime import datetime


def mdy_to_ymd(d):
    return datetime.strptime(d, '%b %d, %Y').strftime('%Y-%m-%d')

这是一个概念证明:


>>> from datetime import datetime
>>> 
>>> 
>>> def mdy_to_ymd(d):
...     return datetime.strptime(d, '%b %d, %Y').strftime('%Y-%m-%d')
... 
>>> mdy_to_ymd('Jan 25, 2021')
'2021-01-25'
>>> 

请记住,strptime() 根据使用掩码字符格式匹配日期的 datetime 创建 string 对象。在 datetime 对象中获得正确的掩码和正确的表示后,您可以使用 strftime() 将其转换为所需的格式。

有关详细信息,请查看 strftime() and strptime() Format Codes

答案 1 :(得分:-1)

你可以使用

date_like_you_dont_want = "Jan 2,2021".lower()

day = date_like_you_dont_want[4:6]

if not ',' in day:
    year = date_like_you_dont_want[7:]
else:
    day=date_like_you_dont_want[4]
    year=date_like_you_dont_want[6:]

month=date_like_you_dont_want[:3]
if month =='jan':
    month = '01'
elif month =='fev':
    month = '02'
elif month =='mar':
    month = '03'
elif month =='may':
    month = '04'
elif month =='apr':
    month = '05'
elif month =='jun':
    month = '06'
elif month =='jul':
    month = '07'
elif month =='aug':
    month = '08'
elif month =='sep':
    month = '09'
elif month =='oct':
    month = '10'
elif month =='mov':
    month = '11'
elif month =='dez':
    month = '12'

print(year+'-'+day+'-'+month)