Parse date string and change format

后端 未结 9 662
孤街浪徒
孤街浪徒 2020-11-22 00:58

I have a date string with the format \'Mon Feb 15 2010\'. I want to change the format to \'15/02/2010\'. How can I do this?

9条回答
  •  感情败类
    2020-11-22 01:43

    As this question comes often, here is the simple explanation.

    datetime or time module has two important functions.

    • strftime - creates a string representation of date or time from a datetime or time object.
    • strptime - creates a datetime or time object from a string.

    In both cases, we need a formating string. It is the representation that tells how the date or time is formatted in your string.

    Now lets assume we have a date object.

    >>> from datetime import datetime
    >>> d = datetime(2010, 2, 15)
    >>> d
    datetime.datetime(2010, 2, 15, 0, 0)
    

    If we want to create a string from this date in the format 'Mon Feb 15 2010'

    >>> s = d.strftime('%a %b %d %y')
    >>> print s
    Mon Feb 15 10
    

    Lets assume we want to convert this s again to a datetime object.

    >>> new_date = datetime.strptime(s, '%a %b %d %y')
    >>> print new_date
    2010-02-15 00:00:00
    

    Refer This document all formatting directives regarding datetime.

提交回复
热议问题