Convert Python date to Unix timestamp - python-2.7

I would like to convert a Python date object to a Unix timestamp.
I already added a time object, so it would be that specific date at midnight, but I don't know how to continue from there.
d = date(2014, 10, 27)
t = time(0, 0, 0)
dt = datetime.combine(d, t)
#How to convert this to Unix timestamp?
I am using Python 2.7

You can get the unix time like this:
import time
from datetime import date
d = date(2014, 10, 27)
unixtime = time.mktime(d.timetuple())

Unix time can be derived from a datetime object like this:
d = date(2014, 10, 27)
t = time(0, 0, 0)
dt = datetime.combine(d, t)
unix = dt.strftime('%s')
# returns 1414364400, which is 2014-10-27 00:00:00

You can use easy_date to make it easy:
import date_converter
timestamp = date_converter.date_to_timestamp(d)

>>> import datetime
>>> d = datetime.date(2014, 10, 27)
>>> int("{:%s}".format(d))
1414364400
>>> datetime.datetime.fromtimestamp(1414364400)
datetime.datetime(2014, 10, 27, 0, 0)
Please note that %s formatting of times is not supported on Windows.

Related

Difference between two dates python/Django

I need to know how to get the time elapsed between the edit_date(a column from one of my models) and datetime.now(). My edit_date column is under the DateTimeField format. (I'm using Python 2.7 and Django 1.10)
This is the function I'm trying to do:
def time_in_status(request):
for item in Reporteots.objects.exclude(edit_date__exact=None):
date_format = "%Y-%m-%d %H:%M:%S"
a = datetime.now()
b = item.edit_date
c = a - b
dif = divmod(c.days * 86400 + c.minute, 60)
days = str(dif)
print days
The only thing I'm getting from this fuction are the minutes elapsed and seconds. What I need is to get this date in the following format:
Time_elapsed = 3d 47m 23s
Any ideas? let me know if I'm not clear of if you need more information
Thanks for your attention,
Take a look at dateutil.relativedelta:
http://dateutil.readthedocs.io/en/stable/relativedelta.html
from dateutil.relativedelta import relativedelta
from datetime import datetime
now = datetime.now()
ago = datetime(2017, 2, 11, 13, 5, 22)
diff = relativedelta(ago, now)
print "%dd %dm %ds" % (diff.days, diff.minutes, diff.seconds)
I did that code from memory, so you may have to tweak it to your needs.
Try something like
c = a - b
minutes = (c.seconds % 3600) // 60
seconds = c.seconds % 60
print "%sd %sm %ss" % (c.days, minutes, seconds)

How to turn Python integer into datetime

I have a simple PyQt GUI which gives values which I would like to turn into a datetime format.
At the moment it is printing
201011
Whereas I would like it to print
2010,1,1
Here is the PyQt code,
*timer.py
from PyQt4 import QtCore, QtGui
try:
_fromUtf8 = QtCore.QString.fromUtf8
except AttributeError:
def _fromUtf8(s):
return s
try:
_encoding = QtGui.QApplication.UnicodeUTF8
def _translate(context, text, disambig):
return QtGui.QApplication.translate(context, text, disambig, _encoding)
except AttributeError:
def _translate(context, text, disambig):
return QtGui.QApplication.translate(context, text, disambig)
class Ui_Dialog(object):
def setupUi(self, Dialog):
Dialog.setObjectName(_fromUtf8("Dialog"))
Dialog.resize(510, 129)
self.gridLayout = QtGui.QGridLayout(Dialog)
self.gridLayout.setObjectName(_fromUtf8("gridLayout"))
self.frame = QtGui.QFrame(Dialog)
self.frame.setFrameShape(QtGui.QFrame.StyledPanel)
self.frame.setFrameShadow(QtGui.QFrame.Raised)
self.frame.setObjectName(_fromUtf8("frame"))
self.gridLayout_2 = QtGui.QGridLayout(self.frame)
self.gridLayout_2.setObjectName(_fromUtf8("gridLayout_2"))
self.yearlabel = QtGui.QLabel(self.frame)
self.yearlabel.setObjectName(_fromUtf8("yearlabel"))
self.gridLayout_2.addWidget(self.yearlabel, 0, 0, 1, 1)
self.monthfromcomboBox = QtGui.QComboBox(self.frame)
self.monthfromcomboBox.setObjectName(_fromUtf8("monthfromcomboBox"))
self.gridLayout_2.addWidget(self.monthfromcomboBox, 1, 2, 1, 2)
self.label_2 = QtGui.QLabel(self.frame)
self.label_2.setObjectName(_fromUtf8("label_2"))
self.gridLayout_2.addWidget(self.label_2, 0, 4, 1, 1)
self.SearchButton = QtGui.QPushButton(self.frame)
self.SearchButton.setObjectName(_fromUtf8("SearchButton"))
self.gridLayout_2.addWidget(self.SearchButton, 2, 4, 1, 2)
self.yearfromcomboBox = QtGui.QComboBox(self.frame)
self.yearfromcomboBox.setObjectName(_fromUtf8("yearfromcomboBox"))
self.gridLayout_2.addWidget(self.yearfromcomboBox, 1, 0, 1, 2)
self.dayfromcomboBox = QtGui.QComboBox(self.frame)
self.dayfromcomboBox.setObjectName(_fromUtf8("dayfromcomboBox"))
self.gridLayout_2.addWidget(self.dayfromcomboBox, 1, 4, 1, 2)
self.label = QtGui.QLabel(self.frame)
self.label.setObjectName(_fromUtf8("label"))
self.gridLayout_2.addWidget(self.label, 0, 2, 1, 1)
self.gridLayout.addWidget(self.frame, 0, 0, 1, 1)
self.retranslateUi(Dialog)
QtCore.QMetaObject.connectSlotsByName(Dialog)
Dialog.setTabOrder(self.yearfromcomboBox, self.monthfromcomboBox)
Dialog.setTabOrder(self.monthfromcomboBox, self.dayfromcomboBox)
def retranslateUi(self, Dialog):
Dialog.setWindowTitle(_translate("Dialog", "Dialog", None))
self.yearlabel.setText(_translate("Dialog", "Year", None))
self.label_2.setText(_translate("Dialog", "Day", None))
self.SearchButton.setText(_translate("Dialog", "Go", None))
self.label.setText(_translate("Dialog", "Month", None))
The corresponding python code is,
import sys
import datetime
from PyQt4 import QtCore, QtGui
from timer import *
from PyQt4.QtGui import (QApplication, QTabWidget, QWidget,
QStyle, QStyleFactory)
class Window(QtGui.QDialog):
def __init__(self, parent=None):
QtGui.QWidget.__init__(self, parent)
self.ui = Ui_Dialog()
self.ui.setupUi(self)
style = QStyleFactory.create('Cleanlooks')
app.setStyle(style)
QtCore.QObject.connect(self.ui.SearchButton, QtCore.SIGNAL('clicked()'), self.search)
months = range(1,13)
for iitem in months:
Months = str(iitem)
self.ui.monthfromcomboBox.addItem(Months)
days = range(1,32)
for iitem in days:
Days = str(iitem)
self.ui.dayfromcomboBox.addItem(Days)
years = range(2010, 2017)
for iitem in years:
Years = str(iitem)
self.ui.yearfromcomboBox.addItem(Years)
def search(self):
nowyear = int(self.ui.yearfromcomboBox.currentText())
nowmonth = int(self.ui.monthfromcomboBox.currentText())
nowday = int(self.ui.dayfromcomboBox.currentText())
nowdate = int('%d%d%d' %(nowyear,nowmonth,nowday))
print nowdate
if __name__ == "__main__":
app = QtGui.QApplication(sys.argv)
viewer = Window()
viewer.show()
sys.exit(app.exec_())
I'd recommend using datetime.datetime.strptime:
from datetime import datetime
date_int = 201011
date = datetime.strptime(str(date_int), '%Y%m%d')
print '{},{},{}'.format(date.year, date.month, date.day)
2010,1,1
Here is my solution:
dateNum = 201011
dateNum = str(dateNum)
year = dateNum[:4]
monthDay = dateNum[4:]
if len(monthDay) == 2:
day = monthDay[1:]
month = monthDay[:1]
print(year + "," + month + "," + day)
This will output:
2010,1,1
The only problem with this code is that you cannot determine dates such as:
2014111 which should be November 1st but could also be January 11th
Is there any way you can change the format to include leading zeros? (e.g. 20141101 for Nov 1st 2014)
Maybe someone else has a way to determine this. However I think logically the format makes it impossible to determine one or the other.
This code is redefined to handle the leading zeros:
dateNum = 20100101
dateNum = str(dateNum)
year = dateNum[:4]
monthDay = dateNum[4:]
day = monthDay[2:]
month = monthDay[:2]
print(year + "," + month + "," + day)
2010,01,01
There's no reason to convert your date parts into a string and then to an single integer if you don't actually need that integer for something. Get rid of this line:
nowdate = int('%d%d%d' %(nowyear,nowmonth,nowday))
And instead use the individiual date components however you want. It could be as simple as print nowyear, nowmonth, nowday (which will print them separated by spaces), or you could do something more complicated like using them to create something from the datetime module which you can use later (or print in a wide variety of formats).
To get the output you specifically request ('2010,1,1'), you can keep it pretty close to your existing code. Just use print '%d,%d,%d' % (nowyear, nowmonth, nowday), or if you want to use the newer str.format syntax, print '{:d},{:d},{:d}'.format(nowyear, nowmonth, nowday). If you wanted the single-digit month or days to use two characters (so they're always the same width), you could use %02d or {:02d} in the format strings, to request zero-padding to a width of two.

Django annotate group by month

How to sum price group by month?
I try.
import itertools
qs = Contract.objects.values('created', 'proposal__price')
grouped = itertools.groupby(qs, lambda d: d.get('created').strftime('%Y-%m'))
data = [{'month': month, 'quant': sum(list(this_day))} for month, this_day in grouped]
print(data)
But result is no expected.
I need this similar result
[{'month': '2016-04', 'quant': 8650}, {'month': '2016-05', 'quant': 9050}]
Your this_day inside sum(list(this_day)) is a dict, so you need to build a list with a list comprehension. Example
>>> import itertools
>>> from django.contrib.auth.models import User
>>> li = User.objects.all().values('date_joined', 'username')
>>> gr = itertools.groupby(li, lambda d: d.get('date_joined').strftime('%Y-%m'))
>>> dt = [{'m': m, 'q': sum([len(x['username']) for x in q])} for m, q in gr]
>>> dt
[{'m': '2005-06', 'q': 11}, {'m': '2006-10', 'q': 22},
{'m': '2005-06', 'q': 179}, {'m': '2006-08', 'q': 10},
{'m': '2006-09', 'q': 30}, {'m': '2005-06', 'q': 74}, ... ]
Or, for your code, probably something like this
data = [{'month': month, 'quant': sum([x['proposal__price'] for x in this_day])}
for month, this_day in grouped]
Start by extracting the month and all your values
from django.db import connection
select = {'month': connection.ops.date_trunc_sql('month', 'created')}
qs = Contract.objects.extra(select=select).values('month').annotate(my_total=Sum('proposal__price'))
Now we can use a function to group by dict keys like so:
from itertools import groupby
from operator import attrgetter
get_y = attrgetter('month')
from collections import defaultdict, Counter
def solve(dataset, group_by_key, sum_value_keys):
dic = defaultdict(Counter)
for item in dataset:
key = item[group_by_key]
vals = {k:item[k] for k in sum_value_keys}
dic[key].update(vals)
return dic
Apply it to your queryset's newly annotated my_total, grouped by month:
solved = solve(qs, 'month', ['my_total'])
And you'll have grouped sums by month (month being a datetime object you can change manipulate to meet your needs):
for i in solved: print(i, ":", solved[i]['my_total'])
>>> datetime.datetime(2015, 9, 1, 0, 0, tzinfo=<UTC>) : 67614.23
>>> datetime.datetime(2015, 1, 1, 0, 0, tzinfo=<UTC>) : 54792.39
Now you can extract those values :)
My code adapted from #C14L.
import itertools
# from .models import Contract
c = Contract.objects.all().values('created', 'proposal__price')
gr = itertools.groupby(c, lambda d: d.get('created').strftime('%Y-%m'))
dt = [{'month': month, 'quant': sum([x['proposal__price'] for x in quant])} for month, quant in gr]
dt
Thanks.

django compare date with date

I trying to refuse importing lines with date lesser than already imported.
timelimit = Operation.objects.filter(account = 3).aggregate(Max('date'))
for row in csv.reader(reencode(f), delimiter=';', quotechar='"')
if row != []:
if row[0]>timelimit:
operation.date=row[0]
row looks like:
2012-01-12,something,0,something2
Of course comparison row[0]>timelimit is wrong - but what is correct?
#this will convert your string("2012-01-12") to a datetime object
from datetime import datetime
>>> x = datetime.strptime(row[0], "%Y-%m-%d")
>>> x
>>> datetime.datetime(2012, 1, 12, 0, 0)
And then you can convert timelimit in a datetime object too like so:
timelimit = datetime(2011, 10, 10)
and then comparing these two is trivial:
x > timelimit

only apply date format to date columns with xlwt

I have results from a database search where some columns have dates, but not others. I need help to write
data = [['556644', 'Mr', 'So', 'And', 'So', Decimal('0.0000'), datetime.datetime(2012, 2, 25, 0, 0), '', False, datetime.datetime(2013, 6, 30, 0, 0)],...]
into an Excel spreadsheet so that
easyxf(num_format_str='DD/MM/YYYY')
is only applied to the datetime columns. I'm quite new to Python and I've been banging my head on this for quite a few days now. Thanks!
After simplifying your self-answer:
date_xf = easyxf(num_format_str='DD/MM/YYYY') # sets date format in Excel
data = [list(n) for n in cursor.fetchall()]
for row_index, row_contents in enumerate(data):
for column_index, cell_value in enumerate(row_contents):
if isinstance(cell_value, datetime.date):
sheet1.write(row_index+1, column_index, cell_value, date_xf)
else:
sheet1.write(row_index+1, column_index, cell_value)
This is being imported from the SQL server with pyodbc, so that's from where cursor.fetchall() is coming:
data = [list(n) for n in cursor.fetchall()]
for row_index, row_contents in enumerate(data):
for column_index, cell_value in enumerate(row_contents):
xf=None
if isinstance(data[row_index][column_index], datetime.date):
xf = easyxf(num_format_str='DD/MM/YYYY') # sets date format in Excel
if xf:
sheet1.write(row_index+1, column_index, cell_value, xf)
else:
sheet1.write(row_index+1, column_index, cell_value)
Done! :)
Want to write a date to a cell in Excel:
Add an extra attribute to the write call - the style for the cell:
import datetime
import xlwt
workbook = xlwt.Workbook()
worksheet = workbook.add_sheet('test')
date_style = xlwt.easyxf(num_format_str='YYYY/MM/DD')
worksheet.write(0, 0, 'Today')
worksheet.write(1, 0, datetime.date.today(), date_style)
workbook.save('C:\\data.xls')