Search code examples
pythonmysqldjangodatabasepython-datetime

How can i convert from IntgerField(Timestamp) to python datetime


unban_date = models.IntegerField()

This Output = All the timestamps from the database

I need it to convert to DateTime I came up with this but it does not work as it does not take IntegarField

    intToParser = datetime.datetime.fromtimestamp(unban_date)
    parserToDate = intToParser.strftime('%Y-%b-%d %H:%M:%S')
    print(parserToDate)

This is dJango Models

enter image description here


Solution

  • As far as i have understood you have a field urban_date which you want to convert to datetime and use strftime.

    if i am getting it right then you can use property decorator. You can read more about this here

    For your case, something like this would work.

    # other fields
    unban_date = models.IntegerField()
    
    @property
    def parserToDate(self):
        intToParser = datetime.datetime.fromtimestamp(self.unban_date)
        return intToParser.strftime('%Y-%b-%d %H:%M:%S')
    
          
    

    With this each object of DisplayRecLv will have a parserToDAte attribute. For checking that you verify that with

    >>> obj = DisplayRecLv.objects.first()
    >>> obj.parserToDate
    # some date
    

    Also i would suggest if you are not working with some legacy project then use a datetime field for urban_date itself instead of integer field.