I need to find how many years between the date?
Input
dat = ['Apr 2010', 'Dec 2012']
output like this
{
total_years = 2.8
}
Not sure if this is the best way to do it but it'll work
import datetime
start = datetime.datetime.strptime("Apr 2010", "%b %Y")
end = datetime.datetime.strptime("Dec 2012", "%b %Y")
diff = (end - start).days // 365
Related
Hopefully just a simple question. I want to convert a datetime object to seconds and include the days. I've just noticed that my code skipped the day. Please note times are just an example and not 100% accurate.
Content of oldtime.txt (2 days ago):
2021-09-16 19:34:33.569827
Code:
oldtimefile = open('oldtime.txt', 'r+')
oldtme = oldtimefile.read()
datetimeobj = datetime.strptime(oldtme, "%Y-%m-%d %H:%M:%S.%f")
finaltime = datetime.now() - datetimeobj
print(finaltime.seconds)
If I just print finaltime then I get 1 day, 22:13:30.231916.
Now if we take today's date and time - just for argument sake - (2021-09-18 17:34:33.569827) as now then I actually get 80010 seconds instead of roughly 172800 seconds. It's ignoring the day part.
How can I include the day and convert the entire object to seconds?
Thanks.
Instead of .seconds you can use .total_seconds():
from datetime import datetime
oldtme = "2021-09-16 19:34:33.569827"
datetimeobj = datetime.strptime(oldtme, "%Y-%m-%d %H:%M:%S.%f")
finaltime = datetime.now() - datetimeobj
print(finaltime.total_seconds())
Prints:
164254.768354
I am currently retrieving a date in the format of 2020-09-23T09:03:46.242Z (YYYY-MM-DDThh:mm:ss.sssZ) and I am trying to convert it into Wed Sep 23 09:03:46 2020. Struggling with the string manipulations, does anyone have any ideas?
Essentially my goal is to be able to perform os.time() on the date, but im aware I may need to do some reformatting beforehand.
Any help is greatly appreciated
Thanks, Scott.
local s = '2020-09-23T09:03:46.242Z'
local t = {}
t.year, t.month, t.day, t.hour, t.min, t.sec =
assert(s:match'^(%d+)%-(%d+)%-(%d+)T(%d+):(%d+):(%d+)')
print(os.date('%c', os.time(t)))
Try this:
local function convert (s)
local source_format = '(%d%d%d%d)-(%d%d)-(%d%d)T(%d%d):(%d%d):(%d%d)%.'
local year, month, day, hour, min, sec = string.match( s, source_format )
local unix_time = os.time {
year = tonumber(year),
month = tonumber(month),
day = tonumber(day),
hour = tonumber(hour),
min = tonumber(min),
sec = tonumber(sec)
}
local target_format = '%a %b %d %H:%M:%S %Y'
return os.date( target_format, unix_time )
end
I am trying to change the code in a phyton script for OBS studio to show the dates of coming events from a google calendar. But the output to OBS Studio only shows the same (last) date on every event. The script log shows it as it should be thou...
After struggling to find a way to convert the dictionary items to print in a way that I wanted to show it, I finally thought I had made it work the way I wanted.
I am new to python and have basically just searched for answers to how to solve what I needed to change in the code.
It took me days to find out about datetime.datetime and how strftime could work together, and that I needed to upgrade Dateutil to a more recent version to not get some of the errors I got.
Anyway, since I am new to coding and most of this script has been written by someone else it is somewhat hard for me to see where this problem lies.
it works as it should in the script log but the date in "stime" becomes the same for every event when I send it to "text" in OBS Studio.
If anyone could help me with a solution to this, I would be very happy.
# Time objects using datetime
dt_now = dt.utcnow()
now = dt.utcnow().isoformat() + 'Z' # 'Z' indicates UTC time
#Timeformat
locale.setlocale(locale.LC_TIME, "sv_SE") # swedish
tmfmt = '%d %B, %H:%M '
# Gets events currently happending by setting bounds to events happening within a second of current datetime
events = service.events().list(calendarId=cal_url, timeMin=now, timeMax=(dt_now+datetime.timedelta(7,1)).isoformat() +'Z',
maxResults=max_events, singleEvents=True, orderBy='startTime').execute()
# Logs the events to console
for event in events['items']:
mystart = (event['start']['dateTime'])
stime = dt.strftime(dtparse(mystart), format=tmfmt)
print(stime)
#print(datetime.datetime.utcnow().date())
#print (event['start']['dateTime'])
print(event['summary'])
#print(dt_now("%d %b, %Y"))
# Updates the text for each event
count = 0
stream_event_happening = False
record_event_happening = False
for event in events['items']:
if(count >= max_events):
break
text = stime + "\n" + event['summary']
settings = obs.obs_data_create()
obs.obs_data_set_string(settings, "text", text)
source = obs.obs_get_source_by_name(source_names[count])
obs.obs_source_update(source, settings)
obs.obs_data_release(settings)
obs.obs_source_release(source)
settings2 = obs.obs_data_create()
obs.obs_data_set_string(settings2, "file", "{}/{}.jpg".format(images_path, text))
source2 = obs.obs_get_source_by_name(image_sources[count])
obs.obs_source_update(source2, settings2)
obs.obs_data_release(settings2)
obs.obs_source_release(source2)
count += 1
text = stime + "\n" + event['summary']
shows only the same date but different events...
Wow, just a few minutes later I found a solution on my own... I added:
mystart = (event['start']['dateTime'])
stime = dt.strftime(dtparse(mystart), format=tmfmt)
just before:
text = stime + "\n" + event['summary']
and now it works as it should :)
I need to find the difference between two timestamps in minutes.
I am using Python 3.6.
Here is my script:
import datetime
from dateutil import parser
indate = str(datetime.datetime.utcnow())
indate2 = parser.parse(indate)
indate3 = indate2.date()
intime = indate2.time()
outdate1 = "2019-10-16T06:38:55.000+0000"
outdate2 = parser.parse(outdate1)
outdate3 = outdate2.date()
outtime = outdate2.time()
### ---THEN PRINT DIFFERENCE BETWEEN THE TWO IN MINUTES --- ###
It will be advisable to ensure that they both have the same timezone:
(indate2.astimezone(datetime.timezone.utc) - outdate2).total_seconds()/60
Out[161]: 494.60840941666663
You need to remove the timezone awarenes from outdate2
print(indate2 - outdate2.replace(tzinfo=None))
I'm trying to compare two text files that are date specific, but I'm stumped. I created a test folder that has three text files in it with modified dates between one and 35 days old.
I.E: red.txt is 35 days old, blue.txt is one day old, and green.txt is 15 days old.
For my two compared files, the first file must be between a range of 13-15 days and the second one day old or less. So for this example, 'green.txt' will become 'file1' and 'blue.txt' will become 'file2' and then be compared with difflib, but I'm having trouble with the syntax, or maybe even the logic. I am using datetime with timedelta to try to get this working, but my results will always store the oldest modified file that is past 15 days for 'file1'. Here's my code:
import os, glob, sys, difflib, datetime as d
p_path = 'C:/test/Text_file_compare_test/'
f_list = glob.glob(os.path.join(p_path, '*.txt'))
file1 = ''
file2 = ''
min_days_ago = d.datetime.now() - d.timedelta(days=1)
max_days_ago = d.datetime.now() - d.timedelta(days=13 <= 15)
for file in f_list:
filetime = d.datetime.fromtimestamp(os.path.getmtime(file))
if filetime < max_days_ago:
file1 = file
if filetime > min_days_ago:
file2 = file
with open(file1) as f1, open(file2) as f2:
d = difflib.Differ()
result = list(d.compare(f1.readlines(), f2.readlines()))
sys.stdout.writelines(result)
I'm certain there is something wrong with code:
max_days_ago = d.datetime.now() - d.timedelta(days=13 <= 15)
Maybe I'm just not seeing something in the datetime module that's obvious. Can someone shed some light for me? Also, this is on Windows 10 Python 3.7.2. Thanks in advance!
As per my comment, your d.timedelta(days=13 <= 15) isn't quite right as you are assigning days to a boolean value of true, which will be equivalent to d.timedelta(days=1). You need to store 3 separate time points and do your 13-15 day comparison against two different dates. The code below demonstrates what you are looking for I believe:
import datetime as d
files = {
'red': d.datetime.now() - d.timedelta(days=35),
'blue': d.datetime.now() - d.timedelta(days=0, hours=12),
'green': d.datetime.now() - d.timedelta(days=14),
}
days_ago_1 = d.datetime.now() - d.timedelta(days=1)
days_ago_13 = d.datetime.now() - d.timedelta(days=13)
days_ago_15 = d.datetime.now() - d.timedelta(days=15)
file1 = None
file2 = None
for file, filetime in files.items():
if days_ago_13 >= filetime >= days_ago_15:
file1 = file
elif filetime > days_ago_1:
file2 = file
# need to break out of the loop when we are finished
if file1 and file2:
break
print(file1, file2)
prints green blue