In excel contains details of so many weeks,I need to print only current week number from excel sheet,if only current week conditions matches it should print that
piece of code for that condition but it showing error:
rec_date = datetime.datetime(*xlrd.xldate_as_tuple(rec, inputfp.datemode)).isocalendar()[1]
if rec_date == date.today().isocalendar()[1]:
print '\n',rec_date
print str(out[rec])
Showing error:
if rec_date == date.today():
AttributeError: 'float' object has no attribute 'today'
So I presume you do not import date from datetime but just import datetime. So
if rec_date == datetime.date.today()
shall work. Or from datetime import date
Related
I am trying to load a CSV from GCS which contains timestamps in one of the columns.
When I upload via BQ interface, I get the following error:
Could not parse '2018-05-03 10:25:18.257000000' as DATETIME for field creation_date (position 6) starting at location 678732930 with message 'Invalid datetime string "2018-05-03 10:25:18.257000000"'
Is the issue here the trailing 0's? How would I fix the issue using Python?
Thanks in advance
Yes you are correct. The issue is the trailing 0s. DATETIME field only allows 6 digits at the subsecond value.
Name | Range
DATETIME | 0001-01-01 00:00:00 to 9999-12-31 23:59:59.999999
To remove the trailing 0s, you can use Pandas to convert it to a proper DATETIME format so it can be used in BigQuery. For testing purposes, I used a CSV file that contains a dummy value at column 0 and DATETIME with trailing 0s at column 1.
Test,2018-05-03 10:25:18.257000000
Test1,2018-05-03 10:22:18.123000000
Test2,2018-05-03 10:23:18.234000000
Using this block of code, Pandas will convert column 1 to the proper DATETIME format:
import pandas as pd
df = pd.read_csv("data.csv",header=None) #define your CSV file here
first_column = df.iloc[:, 1] # Change to the location of your DATETIME column
df.iloc[:, 1] = pd.to_datetime(first_column,format='%Y-%m-%d %H:%M:%S.%f') # convert to correct datetime format
df.to_csv("data.csv", header=False, index=False) # write the new values to data.csv
print(df) #print output for testing
This will result to:
Test,2018-05-03 10:25:18.257
Test1,2018-05-03 10:22:18.123
Test2,2018-05-03 10:23:18.234
You can now use the updated CSV file to write to BQ via BQ interface. See result of BQ testing:
I am trying to create a new datetime column from existing columns (one datetime column and another integer column) in a pandas data frame. Here is my code:
import datetime
df['start_date'] = pd.to_datetime(df['start_date'])
df['end_date'] = df['start_date'] + pd.Timedelta(df.total_waiting_days, unit='D')
But I got the following errors:
ValueError: Value must be Timedelta, string, integer, float, timedelta or convertible
What did I do wrong here and how do I fix this? Thanks!
Seems like you want to convert whole column to Timedelta
df['end_date'] = df['start_date'] + df.total_waiting_days.apply(lambda x :pd.Timedelta(x, unit='D'))
I am trying to pass a date into Oracle 2 different ways when running Python code.
Be able to pull the first day of last month and the last day of last month automatically from datetime.date. I found this code online, but not sure that it will produce the first day of last month and the the last day of last month.
import datetime
today = datetime.date.today()
first = datetime.date(day=1, month=today.month, year=today.year)
lastMonth = first - datetime.timedelta(days=1)
In case of situations that I will need to manually enter the date for prior dates, etc. I want to be able to manually enter a beginning and end date. First off is there a way to have Python prompt me to enter start date and end date? Secondly, I can't seem to get my code to work correctly when I try to put the dates in my code.
Import dateutil.parse
start = dateutil.parser.parse('06/01/2015')
end = dateutil.parser.parse('06/30/2015')
startdate = start.strftime('%d-%b-%y')
enddate = end.strftime('%d-%b-%y')
cursor = con.cursor()
cursor.execute(SELECT * From Executives WHERE DateAdded >= %s And DateAdded <= %s), (startdate, enddate)
I have even tried DateAdded >= :s and DateAdded <= :e. but I am still getting an error.
I need the date in a regular form.
Here when I use the below code:
import sys
from PyQt4.QtGui import *
from PyQt4.QtCore import *
date = QDate.currentDate()
print date
I get the below output:
PyQt4.QtCore.QDate(2014, 5, 23)
I want the date to be displayed in '/' or '.' eg.(5.23.2014)
Please suggest how to do it.
Check the docs:
date = QDate.currentDate().toString("dd.MM.yyyy")
print date
2014.5.23
To change:
date = QDate.currentDate().toString("MM.dd.yyyy")
print date
05.23.2014
Does anyone know how I can sort (in this instance date) my django query set against todays date ?
class Person(models.Model):
name = models.CharField(max_length=50)
date = models.DateField()
My goal is to list the name and date entries. At the top of the list will be the entry with the date that is closest to todays date (day/month).
You can use extra queryset method to select additional data from database table.
This is example that works with MySql:
Person.objects.extra(select={
'datediff': 'ABS(DATEDIFF(date, NOW()))'}).order_by('datediff')
DATEDIFF - returns difference in days bewteen two dates,
ABS - returns absolute value. For sqlite, there is different syntax, see this answer.
EDIT: use current year
Person.objects.extra(select={
'datediff': "ABS(DATEDIFF(CONCAT(YEAR(now()), '-', MONTH(date), '-', DAY(date)), NOW()))"}
).order_by('datediff')
EDIT 2: optimized *
from datetime import date
dayofyear = int(date.today().strftime("%j"))
datediff = 'LEAST(ABS(DAYOFYEAR(date) - %d), ABS((366 - %d + DAYOFYEAR(date))) MOD 366)' % (
dayofyear, dayofyear
)
Person.objects.extra(select={'datediff': datediff}).order_by('datediff')
EDIT 3: closest date after given (todays) date
from datetime import date
dayofyear = int(date.today().strftime("%j"))
datediff = '(DAYOFYEAR(date) - %d + 365) MOD 365' % (
dayofyear
)
Persion.objects.extra(select={'datediff': datediff}).order_by('datediff')
If you want to sort based on date, you can order as: .order_by('date') on a result queryset.
I'm not sure if that answers your question. In case you mean you want to select only the Persons with date of today, you can use:
import datetime
now = datetime.datetime.now()
persons_with_date_today = Person.objects.filter(date=now)