1
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

  • 1
    Why didn't you use datetime field in that case? – targhs Nov 26 '20 at 05:07
  • this might help you https://stackoverflow.com/questions/9744775/how-to-convert-integer-timestamp-to-python-datetime – targhs Nov 26 '20 at 05:08
  • Does this answer your question? [How to convert integer timestamp to Python datetime](https://stackoverflow.com/questions/9744775/how-to-convert-integer-timestamp-to-python-datetime) – targhs Nov 26 '20 at 05:09
  • well, no these are all converting integers to dates, Mine is an IntegarField. They are different things. Those won't take an IntegarField, they will take an Integer or a Float. – Esfar Immam Nov 26 '20 at 05:15
  • Can you show us the code as in where are you converting this? Because urban_date will ultimately return an Integer – targhs Nov 26 '20 at 06:54
  • @TaranjeetSingh I have attached a picture – Esfar Immam Nov 27 '20 at 03:31

1 Answers1

1

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.

targhs
  • 1,477
  • 2
  • 16
  • 29
  • Thanks a lot, that worked like a charm, really appreciate the help. Also learned a lot from this. :) – Esfar Immam Nov 28 '20 at 21:01
  • Welcome. Please upvote also. It would be helpful for other users and make me earn a bit reputation on StackOverflow. – targhs Nov 29 '20 at 17:55