Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
523 views
in Technique[技术] by (71.8m points)

datetime - How to convert string date (Jan 25, 2021) to y-m-d date (2021-01-01) in python

I have strings like Jan 25, 2021 (Jan,Feb,Mar,May,Jun,Jul,Aug,Sep,Oct,Nov,Dec) how can I convert it to 2021-01-25?

I was defining a function like:

def to_datetime(datestring):  
    
    #date = datetime.strptime(datestring, '%m.%d.%Y')
    #return date.strftime("%Y-%m-%d")
    
    return datetime.strptime(datestring, '%Y-%m-%d')

The issue are the month words so maybe I can replace the string to month number and then convert it but I am stuck

question from:https://stackoverflow.com/questions/65894575/how-to-convert-string-date-jan-25-2021-to-y-m-d-date-2021-01-01-in-python

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

As you can see in my comment, you just need to use the right matching mask to get it right.

Your date strings are in the format %b %d, %Y, so you need to use the same mask in strptime(). With that in mind, a function like this will do the job:

from datetime import datetime


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

And here is a proof of concept:


>>> 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'
>>> 

Bear in mind that strptime() creates a datetime object from a string matching a date using masking characters format. Once you get the right mask and the right representation in a datetime object, you can convert it to the desired format using strftime().

For more information, check strftime() and strptime() Format Codes.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...