Amandeep Singh
Amandeep Singh

Reputation: 1431

Convert timestamp to datetimefield and save it in the database

Suppose i have a time stamp as following:

ts=1549366296466

and i have a model which has DateTimeField as follows:

class MyTime(models.Model):
    date_and_time = models.DateTimeField()

Now suppose that there is an object 'o' of class 'MyTime' ? How can i use this time stamp and save it into object 'o'?

o.date_and_time = #I need your help here.
o.save()

I know how to convert this into 'Date Time' format.I can do this using the below method.

import datetime

#First i will convert timestamp into seconds format by dividing by 1000.0
ts = ts/1000.0
#Then i will use this 'ts' in the following line of code.
datetime.utcfromtimestamp(ts).strftime('%Y-%m-%d %H:%M:%S') 

Upvotes: 1

Views: 3884

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 477704

The datetime ojbect has a .utcfromtimestamp method [Python-doc]. The only difference is that this timestamp measures the number of seconds since 1970, not the number of milliseconds, so we can convert this with:

from datetime import datetime

o.date_and_time = datetime.utcfromtimestamp(ts/1000)

This gives us the following two results:

2019-02-05 11:31:36.466000

or for a custom timezone, we can use .fromtimestamp method [Python-doc]:

from dateutil import tz
from datetime import datetime

o.date_and_time = datetime.fromtimestamp(ts/1000, tz=tz.gettz('Asia/Kolkata'))

This then yields:

2019-02-05 17:01:36.466000+05:30

Upvotes: 1

Related Questions