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.
Related
I need a programm on Pyhton3 to check if the user is 18+ or not.
Input: date of the birth. in 4 types of format (25/12/2000,25-12-2000,25.12.2000,25_12_2000)
if wrong print(wrong format)
Output: "welcome to system" or "sorry comeback when you will be 18+"
In case you need my stupid tries:
from datetime import datetime, date
def try_parsing_date(text):
for fmt in ('%d/%m/%Y', '%d.%m.%Y', '%d-%m-%Y', '%d_%m_%Y'):
try:
return datetime.strftime(text,fmt)
except ValueError:
pass
raise ValueError('no valid date format')
dob = input('Введите свой день рождения (дд/мм/гггг): ')
try_parsing_date(dob)
Maybe to deal with it wit regular expressions?
```re_age_checker= "^(0[1-9]|[12][0-9]|3[01])[- \/.,_](0[1-9]|1[012])[- \/.,_](19|20)\d\d"```
Your try was a good start, but you mixed up strftime with strptime; change that.
Maybe to deal with it wit regular expressions?
This is not advisable. After the above change, we can use the result of your function try_parsing_date to compute the 18th birthday and simply compare that to today's date:
dt = try_parsing_date(dob)
import time
# compute the 18th birthday:
d = date.fromtimestamp(time.mktime((dt.year+18, dt.month, dt.day, *(0,)*6)))
if d <= date.today():
print("welcome to system")
else:
print("sorry comeback when you will be 18+")
I am trying to identify dates from a column containing text entries and output the dates to a text file. However, my code is not returning any output. I can't seem to figure out what I did wrong in my code. I'd appreciate some help on this.
My Code:
import csv
from dateutil.parser import parse
with open('file1.txt', 'r') as f_input, open('file2.txt', 'w') as f_output:
csv_input = csv.reader(f_input)
csv_output = csv.writer(f_output)
for row in csv_input:
x = str(row[3])
def is_date(x):
try:
parse(x)
csv_output.writerow([row[0], row[1], row[2], row[3], row[4]])
# no return value in case of success
except ValueError:
return False
is_date(x)
Guessing somewhat you input like e.g.:
1,2,3, This is me on march first of 2018 at 2:15 PM, 2015
3,4,5, She was born at 12pm on 9/11/1980, 2015
a version of what you want could be
from dateutil.parser import parse
with open("input.txt", 'r') as inFilePntr, open("output.txt", 'w') as outFilePntr:
for line in inFilePntr:
clmns = line.split(',')
clmns[3] = parse( clmns[3], fuzzy_with_tokens=True )[0].strftime("%Y-%m-%d %H:%M:%S")
outFilePntr.write( ', '.join(clmns) )
Note, as you do not touch the other columns, I just leave them as text. Hence, no need for csv. You never did anything with the return value of parse. I use the fuzzy token, as my column three has the date somewhat hidden in other text. The returned datetime object is transformed into a string of my liking (see here) and inserted in column three, replacing the old value.
I recombine the strings with comma separation again an write it into output.txt, which looks like:
1, 2, 3, 2018-03-01 14:15:00, 2015
3, 4, 5, 1980-09-11 12:00:00, 2015
I have a small program that I'm working on and I'm having trouble figuring it out.
Given that I have this setup in a csv, how can I check to see if the dates are more than 24 hours old?
CSV sample
Date,Online Status,Username,User Email,Computer ID
2015-05-25,Online,user1,user#example.com,Computer-1
2015-05-25,Online,user2,user#example.com,Computer-2
2015-03-24,Offline,user3,user#example.com,Computer-3
2015-04-17,Offline,user4,user#example.com,Computer-4
2015-05-25,Online,user5,user#example.com,Computer-5
2015-05-25,Online,user6,user#example.com,Computer-6
2015-05-25,Online,user7,user#example.com,Computer-7
2015-05-25,Online,user8,user#example.com,Computer-8
2015-05-25,Online,user9,user#example.com,Computer-9
2015-05-25,Online,user10,user#example.com,Computer-10
What I have so far is this. While it's a good start (I think) I'm not able to do the math I need to get the results I need. Those results are, what computers have been online within the last 24 hours.
Code so far
import csv
from datetime import datetime, timedelta
import logging
DAY = timedelta(seconds=86399)
FORMAT = "%Y-%m-%d"
TODAY = datetime.now().date()
#----------------------------------------------------------------------
def csv_dict_reader(file_obj):
"""
Read a CSV file using csv.DictReader
:param file_obj:
:return: info from the CSV log file
"""
reader = csv.DictReader(file_obj, delimiter=',')
for line in reader:
line["Date"] = datetime.date((line["Date"]))
if (line["Date"] - TODAY) > DAY:
print "Skipped"
else:
print datetime.datetime.strptime(line["Date"], FORMAT)
#----------------------------------------------------------------------
if __name__ == "__main__":
with open("ComputerLog.csv",) as f_obj:
csv_dict_reader(f_obj)
Any help is greatly appreciated.
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
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