timestamp = f'{message.created_at}'
msg_time = datetime.strptime(timestamp, '%Y-%m-%d %H:%M:%S.%f')
now_time = datetime.now()
diff = now_time - msg_time
print('msg_time:', msg_time)
print('now_time:', now_time)
print('diff :', diff)
output :
msg_time: 2022-07-22 06:02:12.934000
now_time: 2022-07-23 01:53:52.375086
diff : 19:51:39.441086
If diff is greater than the time I specify, I want it to send a message to the channel like this:
if diff > 00:01:00.000000:
title2 = "test."
embed2 = discord.Embed(title=title2, color=0xf1c40f)
msg = await channels.send(embed=embed2)
I made it here so that if it's longer than 1 minute, it can be sent, but I don't know exactly, so it doesn't work, how can I do it?
Try using timedelta.total_seconds()
diff = diff.total_seconds()
This will convert the time difference into an integer representing the time in seconds. You can use that value much easier.
References:
https://pythontic.com/datetime/timedelta/total_seconds
https://www.geeksforgeeks.org/python-timedelta-total_seconds-method-with-example/
I I am trying to make a Crypto Barometer. I have a little piece of code that gets the price in USD for each symbol. Now I want to add them up and get the total of these coins (the prices of one of each coin). I got the realtime prices, but I don't know how to add them up. I also want the price of each symbol one, four, eight and 24 hours ago...
In the end it should look like this :
Current 1Hour ... 24Hours
BTCUSDT $49343.34 BTCUSDT $49133.12 BTCUSDT $48763.34
... ... ..
ETHUSDT $2123.84 ETHUSDT $2087.53 ETHUSDT $1987.23
sum : $6255422.23 Sum : $6249983m92 Sum : 6187291.51
Here is my code so far:
import requests
import json
import datetime
import time
api_request = requests.get('https://api.binance.com/api/v3/ticker/price')
api = json.loads(api_request.content)
for x in api:
print(x['symbol'], "${0:.4f}".format(float(x['price'])))
# THE PART WHERE I GOT DIFFERENT TIMES
while True:
dt = datetime
cur_time = (dt.datetime.now().strftime('%d-%m %H:%M'))
one_hour = (dt.datetime.now() - dt.timedelta(hours=1)).strftime('%d-%m %H:%M')
four_hours = (dt.datetime.now() - dt.timedelta(hours=4)).strftime('%d-%m %H:%M')
eight_hours = (dt.datetime.now() - dt.timedelta(hours=8)).strftime('%d-%m %H:%M')
one_day = (dt.datetime.now() - dt.timedelta(hours=24)).strftime('%d-%m %H:%M')
print(cur_time)
print(one_hour)
print(four_hours)
print(eight_hours)
print(one_day)
time.sleep(60)
there is a API library to get prices of nearly every crypto
import cryptocompare
def crypto_price('BTC'):
coin_acronym = str(acronyms['BTC'])
price_crypto = cryptocompare.get_price(coin_acronym, currency='USD', full=True).get('RAW').get(coin_acronym).get(
'USD').get(
'PRICE')
return price_crypto
I need to determine if a flight is a night flight or not. A flight has a departure time and an arrival time.
A nightflight is defined as a flight which encroaches any portion between 00:00 and 02:59.
I have 3 flights with their respective departure and arrival times:
16/01/2018 18:30 → 16/01/2018 20:25 which is not a night flight
16/01/2018 21:35 → 17/01/2018 01:15, which is a night flight
17/01/2018 23:30 → 18/01/2018 03:25, which is a night flight
There is the problem with following code:
def is_night_duty(self):
start_night = time(hour=0, minute=0, second=0)
end_night = time(hour=2, minute=59, second=59)
for flight in self.get_flights():
if start_night <= flight.departure().time.time() <= end_night or start_night<= flight.arrival().time.time() <= end_night:
return True
return False
I want to get start time and end time of yesterday linux timestamp
import time
startDay = time.strftime('%Y-%m-%d 00:00:00')
print startDay
endDay =time.strftime('%Y-%m-%d 23:59:59')
print endDay
Output is:
2016-11-18 00:00:00
2016-11-18 23:59:59
this showing in string today start-time and end-time
I want to get yesterday start-time and end-time in linux time-stamp
like:
4319395200
4319481599
import time
def datetime_timestamp(dt):
time.strptime(dt, '%Y-%m-%d %H:%M:%S')
s = time.mktime(time.strptime(dt, '%Y-%m-%d %H:%M:%S'))
return int(s)
import datetime
midnight2 = datetime.datetime.now().replace(hour=0,minute=0,second=0, microsecond=0)
midnight2 = midnight2 - datetime.timedelta(seconds= +1)
midnight1 = midnight2 - datetime.timedelta(days= +1, seconds= -1)
base = datetime.datetime.fromtimestamp(0)
yesterday = (midnight1 - base).total_seconds()
thismorning = (midnight2 - base).total_seconds()
print midnight1,"timestamp",int(yesterday)
print midnight2,"timestamp",int(thismorning)
print "Seconds elapsed",thismorning - yesterday
Result as of 18/11/2016 :
2016-11-17 00:00:00 timestamp 1479337200
2016-11-17 23:59:59 timestamp 1479423599
Seconds elapsed 86399.0
from datetime import datetime, date, time, timedelta
# get start of today
dt = datetime.combine(date.today(), time(0, 0, 0))
# start of yesterday = one day before start of today
sday_timestamp = int((dt - timedelta(days=1)).timestamp())
# end of yesterday = one second before start of today
eday_timestamp = int((dt - timedelta(seconds=1)).timestamp())
print(sday_timestamp)
print(eday_timestamp)
Or:
# get timestamp of start of today
dt_timestamp = int(datetime.combine(date.today(), time(0, 0, 0)).timestamp())
# start of yesterday = start of today - 86400 seconds
sday_timestamp = dt_timestamp - 86400
# end of yesterday = start of today - 1 second
eday_timestamp = dt_timestamp - 1
Use the power of perl command , no need to import time.
Startday=$(perl -e 'use POSIX;print strftime "%Y-%-m-%d 00:00:00",localtime time-86400;')
Endday=$(perl -e 'use POSIX;print strftime "%Y-%-m-%d 23:59:59",localtime time-86400;')
echo $Startday
echo $Endday
or
startday=date --date='1 day ago' +%Y%m%d\t00:00:00
startday=date --date='1 day ago' +%Y%m%d\t23:59:59
echo $Startday
echo $Endday
I'm currently writing some reporting code that allows users to optionally specify a date range. The way it works (simplified), is:
A user (optionally) specifies a year.
A user (optionally) specifies a month.
A user (optionally) specifies a day.
Here's a code snippet, along with comments describing what I'd like to do:
from datetime import datetime, timedelta
# ...
now = datetime.now()
start_time = now.replace(hour=0, minute=0, second=0, microsecond=0)
stop_time = now
# If the user enters no year, month, or day--then we'll simply run a
# report that only spans the current day (from the start of today to now).
if options['year']:
start_time = start_time.replace(year=options['year'], month=0, day=0)
stop_time = stop_time.replace(year=options['year'])
# If the user specifies a year value, we should set stop_time to the last
# day / minute / hour / second / microsecond of the year, that way we'll
# only generate reports from the start of the specified year, to the end
# of the specified year.
if options['month']:
start_time = start_time.replace(month=options['month'], day=0)
stop_time = stop_time.replace(month=options['month'])
# If the user specifies a month value, then set stop_time to the last
# day / minute / hour / second / microsecond of the specified month, that
# way we'll only generate reports for the specified month.
if options['day']:
start_time = start_time.replace(day=options['day'])
stop_time = stop_time.replace(day=options['day'])
# If the user specifies a day value, then set stop_time to the last moment of
# the current day, so that reports ONLY run on the current day.
I'm trying to find the most elegant way to write the code above--I've been trying to find a way to do it with timedelta, but can't seem to figure it out. Any advice would be appreciated.
To set the stop_time, advance start_time one year, month or day as appropriate, then subtract one timedelta(microseconds=1)
if options['year']:
start_time = start_time.replace(year=options['year'], month=1, day=1)
stop_time = stop_time.replace(year=options['year']+1)-timedelta(microseconds=1)
elif options['month']:
start_time = start_time.replace(month=options['month'], day=1)
months=options['month']%12+1
stop_time = stop_time.replace(month=months,day=1)-timedelta(microseconds=1)
else:
start_time = start_time.replace(day=options['day'])
stop_time = stop_time.replace(day=options['day'])+timedelta(days=1,microseconds=-1)
Using dict.get can simplify your code. It is a bit cleaner than using datetime.replace and timedelta objects.
Here's something to get you started:
from datetime import datetime
options = dict(month=5, day=20)
now = datetime.now()
start_time = datetime(year=options.get('year', now.year),
month=options.get('month', 1),
day=options.get('day', 1)
hour=0,
minute=0,
second=0)
stop_time = datetime(year=options.get('year', now.year),
month=options.get('month', now.month),
day=options.get('day', now.day),
hour=now.hour,
minute=now.minute,
second=now.second)
today = datetime.date.today()
begintime = today.strftime("%Y-%m-%d 00:00:00")
endtime = today.strftime("%Y-%m-%d 23:59:59")
from datetime import datetime, date, timedelta
def get_current_timestamp():
return int(datetime.now().timestamp())
def get_end_today_timestamp():
# get 23:59:59
result = datetime.combine(date.today() + timedelta(days=1), datetime.min.time())
return int(result.timestamp()) - 1
def get_datetime_from_timestamp(timestamp):
return datetime.fromtimestamp(timestamp)
end_today = get_datetime_from_timestamp(get_end_today_timestamp())
date = datetime.strftime('<input date str>')
date.replace(hour=0, minute=0, second=0, microsecond=0) # now we get begin of the day
date += timedelta(days=1, microseconds=-1) # now end of the day
After looking at some of the answers here, and not really finding anything extremely elegant, I did some poking around the standard library and found my current solution (which I like quite well): dateutil.
Here's how I implemented it:
from datetime import date
from dateutil.relativedelta import relativedelta
now = date.today()
stop_time = now + relativedelta(days=1)
start_time = date(
# NOTE: I'm not doing dict.get() since in my implementation, these dict
# keys are guaranteed to exist.
year = options['year'] or now.year,
month = options['month'] or now.month,
day = options['day'] or now.day
)
if options['year']:
start_time = date(year=options['year'] or now.year, month=1, day=1)
stop_time = start_time + relativedelta(years=1)
if options['month']:
start_time = date(
year = options['year'] or now.year,
month = options['month'] or now.month,
day = 1
)
stop_time = start_time + relativedelta(months=1)
if options['day']:
start_time = date(
year = options['year'] or now.year,
month = options['month'] or now.month,
day = options['day'] or now.day,
)
stop_time = start_time + relativedelta(days=1)
# ... do stuff with start_time and stop_time here ...
What I like about this implementation, is that python's dateutil.relativedata.relativedata works really well on edge cases. It gets the days/months/years correct. If I have month=12, and do relativedata(months=1), it'll increment the year and set the month to 1 (works nicely).
Also: in the above implementation, if the user specifies none of the optional dates (year, month, or day)--we'll fallback to a nice default (start_time = this morning, stop_time = tonight), that way we'll default to doing stuff for the current day only.
Thanks to everyone for their answers--they were helpful in my research.