如何在python中通过多种格式格式化日期字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23581128/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 03:11:39  来源:igfitidea点击:

How to format date string via multiple formats in python

pythondatedatetimeformatstrptime

提问by Alexey Sh.

I have three date formats: YYYY-MM-DD, DD.MM.YYYY, DD/MM/YYYY.

我有三种日期格式:YYYY-MM-DD, DD.MM.YYYY, DD/MM/YYYY.

Is it possible to validate and parse strings such as 2014-05-18or 18.5.2014or 18/05/2019?

是否可以验证和解析诸如2014-05-18or18.5.2014或 or 之类的字符串18/05/2019

采纳答案by Jon Clements

Try each format and see if it works:

尝试每种格式,看看它是否有效:

from datetime import datetime

def try_parsing_date(text):
    for fmt in ('%Y-%m-%d', '%d.%m.%Y', '%d/%m/%Y'):
        try:
            return datetime.strptime(text, fmt)
        except ValueError:
            pass
    raise ValueError('no valid date format found')

回答by Gabriel M

Pure python:

纯蟒蛇:

from datetime import datetime
my_datetime = datetime.strptime('2014-05-18', '%Y-%m-%d') 
repr(my_datetime)

>>> 'datetime.datetime(2014,5,18,0,0)'

Check datetime.strptime() format documentation for more format strings.

检查 datetime.strptime() 格式文档以获取更多格式字符串。

回答by khan

>>> import dateutil.parser
>>> dateutil.parser.parse(date_string)

This should take care of most of the standard date formats in Python 2.7+. If you really have super custom date formats, you can always fall back to the one mentioned by Jon Clements.

这应该处理 Python 2.7+ 中的大多数标准日期格式。如果你真的有超级自定义的日期格式,你总是可以回到 Jon Clements 提到的那种。

回答by user3615696

This actually a problem i was facing and this how i approached it, my main purpose was to the date seperators

这实际上是我面临的一个问题以及我如何处理它,我的主要目的是日期分隔符

class InputRequest:
     "This class contain all inputs function that will be required in this program. "

      def __init__(self, stockTickerName = 'YHOO', stockSite='yahoo', startDate = None, 
             endDate = datetime.date.today()):

      def requestInput(self, requestType =''):
          "Fro requesting input from user"
          self.__requestInput = input(requestType)
          return self.__requestInput


def dateFormat(self, dateType=''):
    '''
        this function handles user date input
        this repeats until the correct format is supplied
        dataType: this is the type of date, eg: DOF, Date of Arriveal, etc 

    '''
    while True:
        try:
            dateString = InputRequest.requestInput(self,dateType)
            dtFormat = ('%Y/%m/%d','%Y-%m-%d','%Y.%m.%d','%Y,%m,%d','%Y\%m\%d') #you can add extra formats needed
            for i in dtFormat:
                try:
                    return datetime.datetime.strptime(dateString, i).strftime(i)
                except ValueError:
                    pass

        except ValueError:
            pass
        print('\nNo valid date format found. Try again:')
        print("Date must be seperated by either [/ - , . \] (eg: 2012/12/31 --> ): ")