13

In a Django project of mine, I'm using DateTimeField in a model. This essentially has python datetime.datetime instances.

What's the fastest way convert this to time since epoch (in seconds)?

Hassan Baig
  • 15,055
  • 27
  • 102
  • 205
  • 4
    I disagree that this is a duplicate. If you have a datetime field Django and you want the unix timestamp you do the following: `Project.objects.get(id=1)`. Now the timestamp is accessible via `Project.objects.get(id=1)[0]['created_at'].timestamp()` – Richard Jan 31 '20 at 17:27

2 Answers2

29

In Python 3.3+ you can use datetime.timestamp():

>>> datetime.datetime(2012,4,1,0,0).timestamp()
1333234800.0

For earlier version of Python, you can do:

# Format it into seconds
>>> datetime.datetime(2012,04,01,0,0).strftime('%s')
'1333234800'

# OR, subtract the time with 1 Jan, 1970 i.e start of epoch time
# get the difference of seconds using `total_seconds()`
>>> (datetime.datetime(2012,04,01,0,0) - datetime.datetime(1970,1,1)).total_seconds()
1333238400.0
Moinuddin Quadri
  • 46,825
  • 13
  • 96
  • 126
3
datetime.datetime(date).strftime('%s')

I think it would work for you.

smottt
  • 3,272
  • 11
  • 37
  • 44
Afsal Salim
  • 486
  • 3
  • 14