how to convert unix timestamp to datetime in django's templete? - django

First:
My database is Mysql,and the table has exists,it been used for php,all the time fileds'type is unix_timestamp.
the query result return an unix timestamp string. how to convert the unix timestamp to datetime in django's templete?
second:
about regex,
my code here:
import re
pattern=re.compile("^\d+$")
if pattern.match(50):
print 1
else:
print 0
but it show me "TypeError" why ?
Thanks!
My english is very pool~! I'm sorry

Second:
import re
pattern=re.compile(r"^\d+$")
if pattern.match(u"50"):
print 1
else:
print 0
First:
I can offer a custom template filter, which converts timestamp to python datetime object:
#register.filter(name='fromunix')
def fromunix(value):
return datetime.datetime.fromtimestamp(int(value))
Template:
{{ obj.unixtime|fromunix|date:"F" }}}
https://docs.djangoproject.com/en/dev/howto/custom-template-tags/#registering-custom-filters

Related

Reversing the result of Django's naturaltime

Django's humanize module is fantastic for turning datetime objects into something that makes more sense to us as humans with it's naturaltime function (docs). What I'm trying to do is the reverse, taking any one of the naturaltime formats and converting it back to a datetime (accepting the obvious loss of precision).
Is there any existing library to do this or am I going to have to write my own datetime.strptime patterns?
I know this is a bit of a "find me a tool/library" question, but I've googled around quite a bit with no results.
For any future searchers, I ended up writing dehumanize to handle this question. It's on github here.
from datetime import datetime, timedelta
import re
def naturaltime(text, now=None):
"""Convert a django naturaltime string to a datetime object."""
if not now:
now = datetime.now()
if text == 'now':
return now
if "ago" in text:
multiplier = -1
elif "from now" in text:
multiplier = 1
else:
raise ValueError("%s is not a valid naturaltime" % text)
text = text.replace('an ', '1 ')
text = text.replace('a ', '1 ')
days = get_first(r'(\d*) day', text)
hours = get_first(r'(\d*) hour', text)
minutes = get_first(r'(\d*) minute', text)
seconds = get_first(r'(\d*) second', text)
delta = timedelta(days=days, hours=hours, minutes=minutes, seconds=seconds)
delta *= multiplier
return now + delta
def get_first(pattern, text):
"""Return either a matched number or 0."""
matches = re.findall(pattern, text)
if matches:
return int(matches[0])
else:
return 0

part of a string contained in another string regex python

Is there a way to check if any part of a string matches with another string in python?
For e.g.: I have URLs which look like this
url = pd.DataFrame({'urls' : ['www.amazon.com/ANASTASIA-Beverly...Brow/dp/B00GI21NZA', 'www.ulta.com/beautyservices/benefitbrowbar/']})
and I have strings which look like:
string_list = ['Benefit Cosmetics', 'Anastasia Beverly Hills']
string = '|'.join(string_list)
I would like to match string with url.
Anastasia Beverly Hills with www.amazon.com/ANASTASIA-Beverly...Brow/dp/B00GI21NZA and
www.ulta.com/beautyservices/benefitbrowbar/ with Benefit Cosmetics.
I've been trying url['urls'].str.contains('('+string+')', case = False) but this does not match.
What;s the correct way to do this?
I can't do it as a regex in one line but here is my attempt using itertools and any:
import pandas as pd
from itertools import product
url = pd.DataFrame({'urls' : ['www.amazon.com/ANASTASIA-Beverly...Brow/dp/B00GI21NZA', 'www.ulta.com/beautyservices/benefitbrowbar/']})
string_list = ['Benefit Cosmetics', 'Anastasia Beverly Hills']
"""
For each of Cartesian product (the different combinations) of
string_list and urls.
"""
for x in list(product(string_list, url['urls'])):
"""
If any of the words in the string (x[0]) are present in
the URL (x[1]) disregarding case.
"""
if any (word.lower() in x[1].lower() for word in x[0].split()):
"""
Show the match.
"""
print ("Match String: %s URL: %s" % (x[0], x[1]))
Outputs:
Match String: Benefit Cosmetics URL: www.ulta.com/beautyservices/benefitbrowbar/
Match String: Anastasia Beverly Hills URL: www.amazon.com/ANASTASIA-Beverly...Brow/dp/B00GI21NZA
Updated:
The way you were looking at it you could alternatively use:
import pandas as pd
import warnings
pd.set_option('display.width', 100)
"""
Supress the warning it will give on a match.
"""
warnings.filterwarnings("ignore", 'This pattern has match groups')
string_list = ['Benefit Cosmetics', 'Anastasia Beverly Hills']
"""
Create a pandas DataFrame.
"""
url = pd.DataFrame({'urls' : ['www.amazon.com/ANASTASIA-Beverly...Brow/dp/B00GI21NZA', 'www.ulta.com/beautyservices/benefitbrowbar/']})
"""
Using one string at a time.
"""
for string in string_list:
"""
Get the individual words in the string and concatenate them
using a pipe to create a regex pattern.
"""
s = "|".join(string.split())
"""
Update the DataFrame with True or False where the regex
matches the URL.
"""
url[string] = url['urls'].str.contains('('+s+')', case = False)
"""
Show the result
"""
print (url)
which would output:
urls Benefit Cosmetics Anastasia Beverly Hills
0 www.amazon.com/ANASTASIA-Beverly...Brow/dp/B00... False True
1 www.ulta.com/beautyservices/benefitbrowbar/ True False
Which I guess, if you want it in a DataFrame, may be better but I prefer the first way.

How to remove unwanted items from a parse file

from googlefinance import getQuotes
import json
import time as t
import re
List = ["A","AA","AAB"]
Time=t.localtime() # Sets variable Time to retrieve date/time info
Date2= ('%d-%d-%d %dh:%dm:%dsec'%(Time[0],Time[1],Time[2],Time[3],Time[4],Time[5])) #formats time stamp
while True:
for i in List:
try: #allows elements to be called and if an error does the next step
Data = json.dumps(getQuotes(i.lower()),indent=1) #retrieves Data from google finance
regex = ('"LastTradePrice": "(.+?)",') #sets parse
pattern = re.compile(regex) #compiles parse
price = re.findall(pattern,Data) #retrieves parse
print(i)
print(price)
except: #sets Error coding
Error = (i + ' Failed to load on: ' + Date2)
print (Error)
It will display the quote as: ['(number)'].
I would like it to only display the number, which means removing the brackets and quotes.
Any help would be great.
Changing:
print(price)
into:
print(price[0])
prints this:
A
42.14
AA
10.13
AAB
0.110
Try to use type() function to know the datatype, in your case type(price)
it the data type is list use print(price[0])
you will get the output (number), for brecess you need to check google data and regex.

Django date string translation to english

I am parsing an excel file with dates in it and the date format changes throughout the document. One of the formats is '19 Mart 1912', 'Mart' is the month name in Turkish.
I want to translate this string into English (using Django's builtin translations) as '19 March 1912'.
I tried:
#views.py
from dataparsers import *
def getEnglishDate(request)
translateDateTimeStr('19 Mart 1912')
#dataparsers.py
from django.utils import translation
def translateDateTimeStr(datestr)
translation.activate('en')
translatedDateStr = _(datestr)
translation.deactivate()
return(translatedDateStr)
But nothing changes and I get the same string...
It appears Django's I18N tools has a hard time translating a string with the presence of number characters. I was able to workaround that with the following method:
def translateDateTimeStr(s):
t = []
w = s.split()
for s in w:
translation.activate('de')
t.append(_(s))
translation.deactivate()
return ' '.join(t)
print translateDateTimeStr('12 March 1912')
>>> 12 März 1912
# Does not work
def translateDateTimeStr(s):
translation.activate('de')
t = _(s)
translation.deactivate()
return t
print translateDateTimeStr('12 March 1912')
>>> 12 March 1912
You'll also want to make sure you have USE_I18N=True in your settings.py and your LOCALE_PATH.

Would DateTimeField() work if I have time in this format 1/7/11 9:15 ? If not what would?

I am importing data from a JSON file and it has the date in the following format 1/7/11 9:15
What would be the best variable type/format to define in order to accept this date as it is? If not what would be the most efficient way to accomplish this task?
Thanks.
"What would be the best variable type/format to define in order to accept this date as it is?"
The DateTimeField.
"If not what would be the most efficient way to accomplish this task?"
You should use the datetime.strptime method from Python's builtin datetime library:
>>> from datetime import datetime
>>> import json
>>> json_datetime = "1/7/11 9:15" # still encoded as JSON
>>> py_datetime = json.loads(json_datetime) # now decoded to a Python string
>>> datetime.strptime(py_datetime, "%m/%d/%y %I:%M") # coerced into a datetime object
datetime.datetime(2011, 1, 7, 9, 15)
# Now you can save this object to a DateTimeField in a Django model.
If you take a look at https://docs.djangoproject.com/en/dev/ref/models/fields/#datetimefield, it says that django uses the python datetime library which is docomented at http://docs.python.org/2/library/datetime.html.
Here is a working example (with many debug prints and step-by-step instructions:
from datetime import datetime
json_datetime = "1/7/11 9:15"
json_date, json_time = json_datetime.split(" ")
print json_date
print json_time
day, month, year = map(int, json_date.split("/")) #maps each string in stringlist resulting from split to an int
year = 2000 + year #be ceareful here! 2 digits for a year may cause trouble!!! (could be 1911 as well)
hours, minutes = map(int, json_time.split(":"))
print day
print month
print year
my_datetime = datetime(year, month, day, hours, minutes)
print my_datetime
#Generate a json date:
new_json_style = "{0}/{1}/{2} {3}:{4}".format(my_datetime.day, my_datetime.month, my_datetime.year, my_datetime.hour, my_datetime.minute)
print new_json_style