Diff between time string and current time without year - python

I want to determine the difference between a date string and the current time.
The problem is that the time string does not contain a year (But the current datetime does, so that would be make trouble on year change?)
Here's my current code:
date_parsed = datetime.strptime('Fri Apr 27 19:09:53', '%a %b %d %H:%M:%S')
current_time = datetime.now()

We can assume that date_parsed occurred during the last 365 days, right?
In that case, use .replace() to change the year of that date, compare it to the current date, and adapt the year according to the result of that comparison: if the date is after now, then the parsed date should be adapted, otherwhise, it's ok:
from datetime import datetime
current_time = datetime.now()
date_parsed = datetime.strptime('Fri Apr 27 14:09:53', '%a %b %d %H:%M:%S').replace(year=current_time.year)
if date_parsed > current_time:
date_parsed = date_parsed.replace(year=current_time.year - 1)
print(date_parsed, current_time, current_time - date_parsed)
E.g. with a date in "the past":
2018-04-27 14:09:53 2018-04-27 18:28:10.484371 4:18:17.484371
E.g. with a date in the "future":
2017-04-30 14:09:53 2018-04-27 18:30:48.864598 362 days, 4:20:55.864598

You could do it with total_seconds and modulo arithmetic, but then I think you have issues with things like leap years. Probably the best way is to try two replacements:
tdiff = current_time - date_parsed.replace(year=current_time.year)
if tdiff.days < 0:
tdiff = current_time - date_parsed.replace(year=current_time.year-1)

You can use .strftime() method to synchronize your string time and current time as following:
from datetime import datetime
date_parsed = datetime.strptime('Fri Apr 27 19:09:53', '%a %b %d %H:%M:%S')
current_time = datetime.now().strftime("%m-%d %H:%M:%S")
date_ = date_parsed.strftime("%m-%d %H:%M:%S")

Related

How to consider previous month first day and previous month last day in timestamp (13 digits--milliseconds) format in python 2.7 and python 3x?

Suppose today is August 28, 2019 i want timestamp of July 1,12:00:00 AM and July 31,23:59:59 PM. In general, I want the previous month date and time irrespective of year.
Alternatively with no additional modules:
from datetime import datetime, timedelta
now = datetime.now()
print(now)
firstOfThisMonth = now.replace(day=1)
print(firstOfThisMonth)
endOfLastMonth = firstOfThisMonth-timedelta(days=1)
print(endOfLastMonth)
firstOfLastMonth = endOfLastMonth.replace(day=1)
print(firstOfLastMonth)
print(firstOfLastMonth.replace(hour=0, minute=0, second=0, microsecond=0))
print(endOfLastMonth.replace(hour=23, minute=59, second=59, microsecond=0))
Outputs the following
2019-08-28 07:36:38.768223
2019-08-01 07:36:38.768223
2019-07-31 07:36:38.768223
2019-07-01 07:36:38.768223
2019-07-01 00:00:00
2019-07-31 23:59:59
The following should work for both Python 3x and Python2.7
from datetime import date
from dateutil.relativedelta import relativedelta
today = date.today()
d = today - relativedelta(months=1)
first_day = date(d.year, d.month, 1)
first_day.strftime('%A %d %B %Y')
#returns first date of the previous month - datetime.date(2019, 7, 1)
last_day = date(today.year, today.month, 1) - relativedelta(days=1)
last_day.strftime('%A %d %B %Y')
# returns the last date of the previous month - datetime.date(2019, 7, 31)
Note - The above code only returns the first and last date, not the time. I don't really understand why can't you just hard code the time in milliseconds since it will always be fixed, irrespective of the date.

Python get last month and year

I am trying to get last month and current year in the format: July 2016.
I have tried (but that didn't work) and it does not print July but the number:
import datetime
now = datetime.datetime.now()
print now.year, now.month(-1)
If you're manipulating dates then the dateutil library is always a great one to have handy for things the Python stdlib doesn't cover easily.
First, install the dateutil library if you haven't already:
pip install python-dateutil
Next:
from datetime import datetime
from dateutil.relativedelta import relativedelta
# Returns the same day of last month if possible otherwise end of month
# (eg: March 31st->29th Feb an July 31st->June 30th)
last_month = datetime.now() - relativedelta(months=1)
# Create string of month name and year...
text = format(last_month, '%B %Y')
Gives you:
'July 2016'
now = datetime.datetime.now()
last_month = now.month-1 if now.month > 1 else 12
last_year = now.year - 1
to get the month name you can use
"Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec".split()[last_month-1]
An alternative solution using Pandas which converts today to a monthly period and then subtracts one (month). Converted to desired format using strftime.
import datetime as dt
import pandas as pd
>>> (pd.Period(dt.datetime.now(), 'M') - 1).strftime('%B %Y')
u'July 2016'
You can use just the Python datetime library to achieve this.
Explanation:
Replace day in today's date with 1, so you get date of first day of this month.
Doing - timedelta(days=1) will give last day of previous month.
format and use '%B %Y' to convert to required format.
import datetime as dt
format(dt.date.today().replace(day=1) - dt.timedelta(days=1), '%B %Y')
>>>'June-2019'
from datetime import date, timedelta
last_month = date.today().replace(day=1) - timedelta(1)
last_month.strftime("%B %Y")
date.today().replace(day=1) gets the first day of current month, substracting 1 day will get last day of last month
def subOneMonth(dt):
day = dt.day
res = dt.replace(day=1) - datetime.timedelta(days =1)
try:
res.replace(day= day)
except ValueError:
pass
return res
print subOneMonth(datetime.datetime(2016,07,11)).strftime('%d, %b %Y')
11, Jun 2016
print subOneMonth(datetime.datetime(2016,01,11)).strftime('%d, %b %Y')
11, Dec 2015
print subOneMonth(datetime.datetime(2016,3,31)).strftime('%d, %b %Y')
29, Feb 2016
from datetime import datetime, timedelta, date, time
#Datetime: 1 month ago
datetime_to = datetime.now().replace(day=15) - timedelta(days=30 * 1)
#Date : 2 months ago
date_to = date.today().replace(day=15) - timedelta(days=30 * 2)
#Date : 12 months ago
date_to = date.today().replace(day=15) - timedelta(days=30 *12)
#Accounting standards: 13 months ago of pervious day
date_ma = (date.today()-timedelta(1)).replace(day=15)-timedelta(days=30*13)
yyyymm = date_ma.strftime('%Y%m') #201909
yyyy = date_ma.strftime('%Y') #2019
#Error Range Test
from datetime import datetime, timedelta, date, time
import pandas as pd
for i in range(1,120):
pdmon = (pd.Period(dt.datetime.now(), 'M')-i).strftime('%Y%m')
wamon = (date.today().replace(day=15)-timedelta(days=30*i)).strftime('%Y%m')
if pdmon != wamon:
print('Incorrect %s months ago:%s,%s' % (i,pdmon,wamon))
break
#Incorrect 37 months ago:201709,201710
import datetime as dt
.replace(day=1) replaces today's date with the first day of the month, simple
subtracting timedelta(1) subtracts 1 day, giving the last day of the previous month
last_month = dt.datetime.today().replace(day=1) - dt.timedelta(1)
user wanted the word July, not the 6th month so updating %m to %B
last_month.strftime("%Y, %B")

How do I find the difference between two times in python in a format?

I was wondering how can I calculate the time difference between two times which have PM and AM next to them for example. I have 12:16:44 pm and 01:01:45 pm but when I use this code:
from datetime import datetime
from datetime import timedelta
s1=12:16:44
s2=01:01:45
FMT = '%H:%M:%S'
tdelta = datetime.strptime(s2), FMT) - datetime.strptime(s1), FMT)
if tdelta.days < 0:
tdelta = timedelta(days=0,
seconds=tdelta.seconds,
microseconds=tdelta.microseconds)
but this is the output I get
12:16:44 | 01:01:45 | Time Difference: -1 day, 12:45:01 but they are both PM values? Thanks
In Python, %H means 24 hour time format. %I is 12 hour format and even then you should specify PM in the string
Try that (and fix syntax errors):
s1='12:16:44 PM'
s2='01:01:45 PM'
FMT = '%I:%M:%S %p'

Year wrong on Epoch time conversion

I'm trying to convert epoch time using Python. However, the year always seems to be wrong. In the below example, it should be 2014.
import time
timestamp = time.strftime("%a, %d %b %Y %H:%M:%S +0000",
time.localtime(1415219530834))
What am I doing wrong?
I get this result:
Sat, 09 Jul 46816 16:20:34 +0000
You are passing time in milliseconds, but it should be in seconds. Divide it by 1000
import time
timestamp = time.strftime("%a, %d %b %Y %H:%M:%S +0000",
time.localtime(1415219530))
result:
'Wed, 05 Nov 2014 15:32:10 +0000'
You've passed a timestamp in milliseconds, but localtime expects a value in seconds.
time.localtime(1415219530834 / 1000)
Try this also
import datetime
datetime.datetime.fromtimestamp(your time in epoch/1000)
Convert time in epoch
int(yourtime.strftime("%s"))*1000
You are getting the Epoch in Milliseconds in Python. You need to get it in seconds for it to work correctly.
Something like
import time
mytime = 1415219530834
seconds = int(mytime/1000)
timestamp = time.strftime("%a, %d %b %Y %H:%M:%S +0000",time.localtime(seconds))

How do I retrieve all RSS entries that are no more than X days old

I am using Python and the RSS feedparser module to retrieve RSS entries. However I only want to retrieve a news item if it is no more than x days old.
For example if x=4 then my Python code should not fetch anything four days older than the current date.
Feedparser allows you to scrape the 'published' date for the entry, however it is of type unicode and I don't know how to convert this into a datetime object.
Here is some example input:
date = 'Thu, 29 May 2014 20:39:20 +0000'
Here is what I have tried:
from datetime import datetime
date_object = datetime.strptime(date, '%a, %d %b %Y %H:%M:%S %z')
This is the error I get:
ValueError: 'z' is a bad directive in format '%a, %d %b %Y %H:%M:%S %z'
This is what I hope to do with it:
from datetime import datetime
a = datetime(today)
b = datetime(RSS_feed_entry_date)
>>> a-b
datetime.timedelta(6, 1)
(a-b).days
6
For this, you already have a time.struct_time look at feed.entries[0].published_parsed
you can use time.mktime to convert this to a timestamp and compare it with time.time() to see how far in the past it is:
An example:
>>> import feedparser
>>> import time
>>> f = feedparser.parse("http://feeds.bbci.co.uk/news/rss.xml")
>>> f.entries[0].published_parsed
time.struct_time(tm_year=2014, tm_mon=5, tm_mday=30, tm_hour=14, tm_min=6, tm_sec=8, tm_wday=4, tm_yday=150, tm_isdst=0)
>>> time.time() - time.mktime(feed.entries[0].published_parsed)
4985.511506080627
obviosuly this will be a different value for you, but if this is less than (in your case) 86400 * 4 (number of seconds in 4 days), it's what you want.
So, concisely
[entry for entry in f.entries if time.time() - time.mktime(entry.published_parsed) < (86400*4)]
would give you your list
from datetime import datetime
date = 'Thu, 29 May 2014 20:39:20 +0000'
if '+' in date:
dateSplit = date.split('+')
offset = '+' + dateSplit[1]
restOfDate = str(dateSplit[0])
date_object = datetime.strptime(restOfDate + ' ' + offset, '%a, %d %b %Y %H:%M:%S ' + offset)
print date_object
Yields 2014-05-29 20:39:20, as I was researching your timezone error I came across this other SO question that says that strptime has trouble with time zones (link to question).

Categories