How to convert integer into date object python?

前端 未结 3 2021
无人共我
无人共我 2020-12-03 01:15

I am creating a module in python, in which I am receiving the date in integer format like 20120213, which signifies the 13th of Feb, 2012. Now, I want to conver

3条回答
  •  渐次进展
    2020-12-03 02:03

    Here is what I believe answers the question (Python 3, with type hints):

    from datetime import date
    
    
    def int2date(argdate: int) -> date:
        """
        If you have date as an integer, use this method to obtain a datetime.date object.
    
        Parameters
        ----------
        argdate : int
          Date as a regular integer value (example: 20160618)
    
        Returns
        -------
        dateandtime.date
          A date object which corresponds to the given value `argdate`.
        """
        year = int(argdate / 10000)
        month = int((argdate % 10000) / 100)
        day = int(argdate % 100)
    
        return date(year, month, day)
    
    
    print(int2date(20160618))
    

    The code above produces the expected 2016-06-18.

提交回复
热议问题