本文整理汇总了Python中datetime函数的典型用法代码示例。如果您正苦于以下问题:Python datetime函数的具体用法?Python datetime怎么用?Python datetime使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了datetime函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: test_sum_of_distance
def test_sum_of_distance(self):
self.data = []
self.data.append(mySport(starttime=datetime(year=2015, month=11, day=24, hour=22, minute=0, second=0), \
endtime=datetime(year=2015, month=11, day=24, hour=22, minute=10, second=0), \
distance=20))
self.result = achievement_judger_in_sport_everyday(self.data)
assert (3 not in self.result), 'incorrect result in sum of distance step 1'
self.data.append(mySport(starttime=datetime(year=2015, month=11, day=24, hour=22, minute=13, second=0), \
endtime=datetime(year=2015, month=11, day=24, hour=22, minute=20, second=0), \
distance=4990))
self.result = achievement_judger_in_sport_everyday(self.data)
assert (3 in self.result), 'incorrect result in sum of distance step 2'
self.data = []
self.data.append(mySport(starttime=datetime(year=2015, month=11, day=24, hour=22, minute=0, second=0), \
endtime=datetime(year=2015, month=11, day=24, hour=22, minute=10, second=0), \
distance=20000))
self.result = achievement_judger_in_sport_everyday(self.data)
assert (13 not in self.result), 'incorrect result in sum of distance step 3'
self.data.append(mySport(starttime=datetime(year=2015, month=11, day=24, hour=22, minute=17, second=0), \
endtime=datetime(year=2015, month=11, day=24, hour=22, minute=20, second=0), \
distance=10000))
self.result = achievement_judger_in_sport_everyday(self.data)
assert (13 not in self.result), 'incorrect result in sum of distance step 4'
self.data.append(mySport(starttime=datetime(year=2015, month=11, day=24, hour=23, minute=17, second=0), \
endtime=datetime(year=2015, month=11, day=24, hour=23, minute=20, second=0), \
distance=40000))
self.result = achievement_judger_in_sport_everyday(self.data)
assert (13 in self.result), 'incorrect result in sum of distance step 5'
print('test_sum_of_distance DONE!')
示例2: parse
def parse(root, UNITS):
value = root.find("./pod[@id='Result']").find('subpod').find('plaintext').text
print value
if value.startswith('~~ '):
value = value.strip('~~ ')
m = __number_re.search(value)
if m:
QUANTITY = float(m.group(1))
UNIT = m.group(2).lower()
if "trillion" in UNIT:
QUANTITY *= pow(10, 12)
elif "billion" in UNIT:
QUANTITY *= pow(10, 9)
elif "million" in UNIT:
QUANTITY *= pow(10, 6)
elif "thousand" in UNIT:
QUANTITY *= pow(10, 3)
elif "date" in UNITS:
try:
print "FUCK YOU 2"
dt = dateparse(str(int(QUANTITY)))
QUANTITY = (dt - datetime.datetime(1970, 1, 1)).total_seconds()
except Exception as e:
raise NameError("Exception")
if not UNITS:
if "$" in value:
UNIT = "dollars"
else:
UNIT = UNITS
else:
# check if it is a date
try:
print value
if len(value) == 4:
epoch = datetime(1970, 1, 1)
t = datetime(int(value), 1, 1)
diff = t-epoch
QUANTITY = diff.total_seconds()
print QUANTITY
else:
print "Not 4 chars"
print value
dt = dateparse(value)
QUANTITY = (dt - datetime.datetime(1970, 1, 1)).total_seconds()
UNIT = "date"
except:
raise NameError('Could not parse!')
print QUANTITY
return (QUANTITY, UNIT)
示例3: test_will_filter_for_january
def test_will_filter_for_january(self):
start_of_january = workhours.build_from_date(datetime(2014, 1, 1))
hours = [start_of_january]
result = hours_filtering.filter_by__current_worksheet_month(datetime(2014, 1, 1), hours)
assert start_of_january in result
示例4: convertDateTime
def convertDateTime(datestring):
"""
Takes in a string representing the date and time in
Hubbard Brook format and return a datetime object
"""
if datestring[0] == "A": #MODIS format
year = int(datestring[1:5])
day = int(datestring[5:])
return datetime(year, 1, 1, 0, 0, 0) + timedelta(day-1)
if datestring[0] == "(": #datetime object format
d = eval(datestring)
return datetime(d[0], d[1], d[2], d[3], d[4], d[5])
try: #MATLAB format
datestring=float(datestring)
return datetime.fromordinal(int(datestring)) + timedelta(days=datestring%1) - timedelta(days = 366)
except: #Hubbard Brook Format
year = int(datestring[:4])
month = int(datestring[5:7])
date = int(datestring[8:10])
hour = int(datestring[11:13])
minute = int(datestring[14:16])
seconds = int(datestring[17:19])
return datetime(year, month, date, hour, minute, seconds)
示例5: test_RRuleLocator
def test_RRuleLocator():
import pylab
import matplotlib.dates as mpldates
import matplotlib.testing.jpl_units as units
from datetime import datetime
import dateutil
units.register()
# This will cause the RRuleLocator to go out of bounds when it tries
# to add padding to the limits, so we make sure it caps at the correct
# boundary values.
t0 = datetime( 1000, 1, 1 )
tf = datetime( 6000, 1, 1 )
fig = pylab.figure()
ax = pylab.subplot( 111 )
ax.set_autoscale_on( True )
ax.plot( [t0, tf], [0.0, 1.0], marker='o' )
rrule = mpldates.rrulewrapper( dateutil.rrule.YEARLY, interval=500 )
locator = mpldates.RRuleLocator( rrule )
ax.xaxis.set_major_locator( locator )
ax.xaxis.set_major_formatter( mpldates.AutoDateFormatter(locator) )
ax.autoscale_view()
fig.autofmt_xdate()
fig.savefig( 'RRuleLocator_bounds' )
示例6: getDateIndex
def getDateIndex(day, month, year):
daysSinceSolstice = (datetime(year,month,day) - datetime(year, 3, 21)).days
if daysSinceSolstice < 0:
daysSinceSolstice += 365
celestialLongitude = daysSinceSolstice*(360/365)
zodiac = floor(celestialLongitude/30)
return zodiac
示例7: xlrd_to_date
def xlrd_to_date(cv):
if not str(cv).isalpha() and len(str(cv)) > 1:
from1900to1970 = datetime(1970,1,1) - datetime(1900,1,1) + timedelta(days=2)
print cv
value = date.fromtimestamp( int(cv) * 86400) - from1900to1970
print value
return value
示例8: testFloating
def testFloating(self):
dt = datetime(1999, 1, 2, 13, 46, tzinfo=self.view.tzinfo.floating)
self.failUnlessEqual(formatTime(self.view, dt), "1:46 PM")
dt = datetime(2022, 9, 17, 2, 11, tzinfo=self.view.tzinfo.floating)
self.failUnlessEqual(formatTime(self.view, dt), "2:11 AM")
示例9: testDefaultTimeZone
def testDefaultTimeZone(self):
dt = datetime(1999, 1, 2, 13, 46, tzinfo=self.view.tzinfo.default)
self.failUnlessEqual(formatTime(self.view, dt), "1:46 PM")
dt = datetime(2022, 9, 17, 2, 11, tzinfo = self.view.tzinfo.default)
self.failUnlessEqual(formatTime(self.view, dt), "2:11 AM")
示例10: crawPriceTrends
def crawPriceTrends(self):
for c in self.sources:
city = c["city"]
if c.has_key("trends"):
print c["trends"]
json = get_json(c["trends"])
year = int(json["time"]["year"])
month = json["time"]["month"]
month = int(re.compile(u"(\\d+)月").findall(month)[0])
last = datetime(year, month, 1)
price_trends = json["currentLevel"]["dealPrice"]["total"]
price_trends.reverse()
for price in price_trends:
print last, price
price = price.encode("utf-8")
row = {"city": city, "district":"月趋势", "total": 0, "price": price, "date": last}
old = self.dao.get_item(row["city"], row["district"], row["date"])
if not old:
self.dao.insert_item(row)
else:
self.dao.update_item(city, "月趋势", 0, price, last)
month -= 1
if month == 0:
year -= 1
month = 12
last = datetime(year, month, 1)
示例11: testNoTimeZone
def testNoTimeZone(self):
dt = datetime(1999, 1, 2, 13, 46)
self.failUnlessEqual(formatTime(self.view, dt), "1:46 PM")
dt = datetime(2022, 9, 17, 2, 11)
self.failUnlessEqual(formatTime(self.view, dt), "2:11 AM")
示例12: get_rates_by_openid
def get_rates_by_openid(openid):
data = []
lowest = 10000
highest = 0
average = 0
count = 0
user = User.query.filter_by(openid = openid).first()
if user == None:
return [], 0, 0, 0
today = date.today()
rates = user.rates.filter(Rate.time >= datetime(today.year, today.month, today.day)).order_by(Rate.time).all()
ctime = datetime(today.year, today.month, today.day)
j = 0
while ctime <= datetime.now():
if j >= len(rates) or rates[j].time > ctime:
data.append(0)
else:
data.append(rate[j].total)
lowest = min(lowest, rate[j].total)
highest = max(highest, rate[j].total)
average += rate[j].total
count += 1
j += 1
ctime += timedelta(minutes = 10)
if count > 0 :
average /= count
return data, average, highest, lowest
示例13: NONBUSICAL
def NONBUSICAL(self):
session = self.sess
date = datetime(2010, 12, 14)
new_busiday = calendar(CALID = 'DECEMBER', DATE=date)
session.add(new_busiday)
session.flush()
new_sch = schedule(SCHEDID = '1 NONBUSIDAY DEC', INTERVAL = 1, METHOD = 0, AFTER=0, DELTA=3, WAIT=0, CALID='DECEMBER', CALTYPE=1)
session.add(new_sch)
session.flush()
new_action = action(ACTIONID = 'TESTACTIONDEC', USERID = self.USERID)
session.add(new_action)
session.flush()
date = datetime(2010, 12, 13, 1, 1, 1)
new_job = job(ACTIONID = 'TESTACTIONDEC', SCHEDID = '1 NONBUSIDAY DEC', SCHDATE=date, STATUS = '2')
session.add(new_job)
session.flush()
new_job.resch(None)
self.assert_(new_job.SCHDATE.strftime("%Y") == '2010', "NONBUSICAL test Invalid Year")
self.assert_(new_job.SCHDATE.strftime("%d") == '14', "NONBUSICAL test Invalid Day")
self.assert_(new_job.SCHDATE.strftime("%m") == '12', "NONBUSICAL test Invalid Month")
self.assert_(new_job.SCHDATE.strftime("%H") == '01', "NONBUSICAL test Invalid Hour")
self.assert_(new_job.SCHDATE.strftime("%M") == '01', "NONBUSICAL test Invalid Minute")
self.assert_(new_job.SCHDATE.strftime("%S") == '01', "NONBUSICAL test Invalid Second")
示例14: datetimef
def datetimef(d,t=None,fmt='%Y-%m-%d'):
""""converts something to a datetime
:param d: can be:
- datetime : result is a copy of d with time optionaly replaced
- date : result is date at time t, (00:00AM by default)
- int or float : if fmt is None, d is considered as Excel date numeric format
(see http://answers.oreilly.com/topic/1694-how-excel-stores-date-and-time-values/ )
- string or speciefied format: result is datetime parsed using specified format string
:param fmt: format string. See http://docs.python.org/2/library/datetime.html#strftime-strptime-behavior
:param t: optional time. replaces the time of the datetime obtained from d. Allows datetimef(date,time)
:return: datetime
"""
if isinstance(d,datetime):
d=d
elif isinstance(d,date):
d=datetime(year=d.year, month=d.month, day=d.day)
elif isinstance(d,(six.integer_types,float)):
d=datetime(year=1900,month=1,day=1)+timedelta(days=d-2) #WHY -2 ?
else:
d=datetime.strptime(str(d),fmt)
if t:
d=d.replace(hour=t.hour,minute=t.minute,second=t.second)
return d
示例15: get_qtd_actions_near_date
def get_qtd_actions_near_date(cop, date):
clusteringDefault = '%Y/%m/%d'
inicioCopaConf = datetime(2013,6,10)
terminoCopaConf = datetime(2013,7,3)
#clusterPorHora = '%Y/%B/%d %H:%m:%S'
sincronizacoes = Sincronizacao.get_all()
tmp = [sinc for sinc in sincronizacoes if sinc.cop_responsavel['id']==cop]
qtde = 0
print len(tmp)
for sinc in sincronizacoes:
actionsDates = []
if (sinc.cop_responsavel['id']== cop or cop == 'TODOS'):
for action in sinc.acoes:
print action.inicio, date - action.inicio
if (
#((action.tipo == 'INTERVALO') and (action.inicio <= date) and (date <=action.fim)) or
#((action.tipo == 'PONTUAL')and (action.inicio <= date))
action.tipo == 'INTERVALO' and
action.inicio >=inicioCopaConf and
action.fim <= terminoCopaConf and
(date - action.inicio).days <= 1 and
(action.fim - date).days <=1
#or
#((action.tipo == 'PONTUAL') and (date - action.inicio).days <= 1)
):
qtde = qtde + len(actionsDates)
return qtde