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
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+")
This question already has answers here:
Apply timezone offset to datetime in Python
(3 answers)
Closed 4 years ago.
from dateutil.parser import parse
from dateutil.relativedelta import relativedelta
from dateutil.tz import gettz
from datetime import datetime, timedelta
input_time = '2019-02-01 09:50:08+11:00'
parsed=parse(input_time)
print parsed.tzinfo
I have a time input string:
input_time = '2019-02-01 09:50:08+11:00'
I want to convert it into this format: YYYY-MM-DD HH:MM:SS. Basically, adding the offset to the actual time object. For the above example I am looking for below output:
input_time_converted = '2019-02-01 20:50:08'
Found some useful stuff in dateutil library to parse the date object passed as a string and get the offset details but it gives me this output:
tzoffset(None, 39600)
But I don't know how to get the actual digits from the above and do the rest of the maths.
I have tried to call it with -as explained in the official dateutil parser documentation-
print parsed.tzinfo.tzoffset
But didn't work.
#!/usr/bin/env python2
def process_messed_up_timestamp(ts):
"""Convert messed up timestamps to something else.
Input timestamp is in UTC format with the offset that
should be applied but hasn't been.
"""
from datetime import datetime, timedelta
timestamp, plus, offset = ts[:19], ts[19], ts[20:]
# should validate plus is '+' or '-'
fmt = '%Y-%m-%d %H:%M:%S'
base = datetime.strptime(timestamp, fmt)
hours, minutes = [int(n) for n in offset.split(':')]
delta = timedelta(hours=hours, minutes=minutes)
multiplier = -1 if plus == '-' else 1
return (base + multiplier * delta).strftime(fmt)
input_time = '2019-02-01 09:50:08+11:00'
input_time_converted = '2019-02-01 20:50:08'
assert process_messed_up_timestamp(input_time) == input_time_converted
programmers! I have a question on how to make a countdown calendar until my piano recital; just as a fun side project. So, keeping that in mind, I created this code:
#!/usr/bin/python
import os
import numpy
import time
import commands
days = 59
(status, txt) = commands.getstatusoutput('date')
txt = txt.replace('EDT','')
txt = txt.replace('2016','')
if 'Mon' in txt:
txt = txt.replace('Mon','')
elif 'Tue' in txt:
txt = txt.replace('Tue','')
elif 'Wed' in txt:
txt = txt.replace('Wed','')
elif 'Thu' in txt:
txt = txt.replace('Thu','')
elif 'Fri' in txt:
txt = txt.replace('Fri','')
elif 'Sat' in txt:
txt = txt.replace('Sat','')
elif 'Sun' in txt:
txt = txt.replace('Sun','')
calc = int(txt) + days
while calc > days:
days = days - 1
if calc == days:
print days
break
else:
continue
However, in the variable date, it includes the time. I don't want the time, I just want the date. How could I do this? Also, please tell me what else is wrong with my code!
- Thanks
You can use datetime module to get the current date only. It will give you the current date without even so much modification on strings.
import datetime
now = datetime.date.today()
print str(now.month) + " " + str(now.day)
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.
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