How to connect commands to calendar - python

import time;
localtime = time.asctime( time.localtime(time.time()) )
print "Local current time :", localtime
I'm trying to figure out how to add write a command like this:
"Next day." That will then print out the next day in the calendar and so forth.
I've managed to get the calendar in, but I'm in need of help on how to connect commands to it. Thanks in advance!

Writing a program that will handle a limited set of expressions entered by the user of the form "Next day" isn't that hard, but if you want to handle arbitrary date query expressions, things get a little complicated. :)
But if you just want to know how to manipulate dates (and times) in Python you will have to read the documentation for the datetime and calendar modules. The datetime module is rather large and a little bit messy, so don't expect to master it immediately. But if you read through the docs and write lots of little test programs you will soon learn how to use it.
To get you started, here's a small example which shows how to add or subtract an arbitrary number of days from a given date. To display the dates this program uses the strftime method, which you've probably already seen in the time module docs.
#!/usr/bin/env python
import datetime
def date_string(date):
return date.strftime('%A %d %B %Y')
oneday = datetime.timedelta(days=1)
today = datetime.date.today()
print today
print 'Today is', date_string(today)
print 'Tomorrow is', date_string(today + oneday)
print 'Yesterday was', date_string(today - oneday)
print 'In one week it will be', date_string(today + oneday * 7)
output
2015-02-24
Today is Tuesday 24 February 2015
Tomorrow is Wednesday 25 February 2015
Yesterday was Monday 23 February 2015
In one week it will be Tuesday 03 March 2015

Related

python method to convert string in format "11th November" into a date

I am using python in scrapy and collecting a bunch of dates that are stored on a web page in the form of text strings like "11th November" (no year is provided).
I was trying to use
startdate = '11th November'
datetime.strptime(startdate, '%d %B')
but I don't think it likes the 'th' and I get a
Value error: time data '11th November' does not match format '%d %B'
If I make a function to try to strip out the th, st, rd, nd from the days I figured it will strip out the same text from the month.
Is there a better way to approach turning this into a date format?
For my use, it ultimately needs to be in the ISO 8601 format YYYY-MM-DD
This is so that I can pipe it from scrapy to a database, and from that use it in a Google Spreadsheet for a javascript Google chart. I just mention this because there may be a better place to make the string-to-date change than trying to do it in python.
(As a secondary issue, I also need to figure how to add the right year to the date given that if it says 12th January that would mean Jan 2020 and not 2019. This will be based on a comparison to the date when the scrape runs. i.e. the date today.)
EDIT:
it turned out that the solution required the secondary issue to be addressed as well. Hence the choice of final answer to this question. If the secondary issue of the year was not addressed it defaulted to 1900 which was a problem.
Try this out -
import datetime
datetime_obj = datetime.datetime.strptime(re.sub(r"\b([0123]?[0-9])(st|th|nd|rd)\b",r"\1", startdate) + " " + str(datetime.datetime.now().year), "%d %B %Y")

Getting milliseconds from the date, but showing one day less than actual

I'm trying to print milliseconds from date in python, I used below code to get millisecond since I'm new to Python I would like to check with someone here if this is that right way of getting milliseconds:
import datetime
def findmili(date):
return int(date.strftime("%s")) * 1000
x = datetime.datetime.strptime('01/27/2017', "%m/%d/%Y")
print findmili(x)
Can someone please help me to validate this, if this is not right way of getting can you tell what's the exact way of getting this in python.
Looks like something wrong, I'm trying to get millisecond of Jan 12 2017 but my program returns this value: 1484179200000. If I convert those milliseconds to a date using this online utility, it shows Jan 11 2017 instead of Jan 12 2017.
Note: I have to use Python 2.7 version only. :(
First of all, I believe a bit of clarification in your question would be to indicate that you are looking for milliseconds that have elapsed from epoch till the date you provide as that is what the tool seems to be doing.
A simple way to do something like that is like this :
int(datetime.datetime.now().strftime("%s")) * 1000
replace datetime.datetime.now() with your own datetime object. So the completed function might be something like this :
import datetime
def findmili(date):
return int(date.strftime("%s")) * 1000
x = datetime.datetime.strptime('10Nov2017', '%d%b%Y')
print findmili(x)
As an aside, your code won't actually run in python2.7. This is because, you have made an error in line 6 where instead of d = datetime.strptime(myDate, "%m/%d/%Y"), it should actually be d = datetime.datetime.strptime(myDate, "%m/%d/%Y")
Another aside, your code is also correct ( except from the error above ) . Its returning 1484150400000 which returns as Thu Jan 12 2017 00:00:00 GMT+0800.
When you use that online site notice that its result depends on where the site believes that you are situated. In the time zone where I live (Eastern Canada) I get the correct result. However, if I change the timezone on the site to the one for Phoenix, Arizona in the United States, for instance, this is the result.
I suspect that this is why you are getting an unexpected result.

Python date comparison with string output/format

I'm currently trying to writing a script to automate a function at work, but I'm not intimately familiar with Python. I'm trying to take a XML dump and compare a specific entry's date to see if the time has passed or not.
The date is in a particular format, given:
<3-letter Month> <DD> <HH:MM:SS> <YYYY> <3-letter Timezone>
For example:
May 14 20:11:20 2014 GMT
I've parsed out a string in that raw form, and need to somehow compare it with the current time to find out if the time has passed or not. That said, I'm having a bit of trouble figuring out how I should go about either formatting my text, or choosing the right mask/time format in Python.
I've been messing around with different variations of the same basic format:
if(trimmed < time.strftime("%x") ):
Trimmed is the clean date/time string. Time is derived from import time.
Is there a simple way to fix this or will I have to dig into converting the format etc.? I know the above attempt is simplistic, but I'm still very new to Python. Thanks for your time and patience!
You should use combination of gmtime (for GMT time),mktime and datetime.
from time import gmtime,mktime
from datetime import datetime
s = "May 14 20:11:20 2014 GMT"
f = "%b %d %H:%M:%S %Y GMT"
dt = datetime.strptime(s, f)
gmt = datetime.fromtimestamp(mktime(gmtime()))
if dt<gmt:
print(dt)
else:
print(gmt)

CPython - Making the date show up using the date on your computer

I'm really new to programming and I only just started using Python, if anyone could edit the code I put up to make it work how I want it to then please do.
I was wondering if I could make the date show up, on my python program but make it different for different regions, so if someone opened the program in United Kingdom the day would show up first and if it was in the US it would show the month or year first etc.
This is what I have so far.
import datetime
currentDate = datetime.date.today()
print(currentDate.strftime('Todays date is: %d %B %Y'))
I currently have it set so it shows the day first then the month then the year.
Is there anyway to make it use it in a different order depending on what country you're in?
Does this work for you?
>>> import datetime
>>> today = datetime.date.today()
>>> print(today.strftime('%x'))
09/10/15
Specifically, you probably should look at the %c, %x, and %X format codes. See 8.1.8. strftime() and strptime() Behavior for more information on how to use the strftime method.

How to import one day old logs

I am new to Python and need some help in being able to import done day old logs. Below is the script I have come up with, but not sure if it is working or if there is a better way to do this.
def fileCreation(path):
now = time.time()
oneday_ago = now - (24*60*60) ## seconds in 1 day
if fileCreation < oneday_ago:
print f
getAuditRecords(f)
I have a script that does import the whole database from mid June 2014 but only need to get day old logs.
Here is a sample of the logs I am trying to import
/mnt/hcp1/R1P/R1P_ora_982_2.xml.201409070400
/mnt/hcp1/R1P/R1P_ora_20_1.xml.201409070400
/mnt/hcp1/R1P/R1P_ora_29962_1.xml.201409070400
/mnt/hcp1/R1P/R1P_ora_15593_2.xml.201409070400
/mnt/hcp1/R1P/R1P_ora_9946_1.xml.201409070400
/mnt/hcp1/R1P/R1P_ora_10746_1.xml.201409070400
/mnt/hcp1/R1P/R1P_ora_6508_1.xml.201409070400
/mnt/hcp1/R1P/R1P_ora_17340_2.xml.201409070400
/mnt/hcp1/SCC/SCC_ora_18881_2.xml.201407090400
In order to compare the file creation time to one day ago, you need to actually get the file creation time. Your code is using fileCreation, the function; it doesn't mean anything useful to ask whether that function is less than some time.
Unfortunately, "file creation time" is not a portable concept. If you really want that, you need to write different code for different platforms, which I won't explain.
Usually, you're happy with "file modification time". This is set when the file is created, and updated only when you overwrite or append to the file. You can use getmtime to read this. So:
def fileCreation(path):
now = time.time()
oneday_ago = now - (24*60*60) ## seconds in 1 day
mtime = os.path.getmtime(path)
if mtime < oneday_ago:
print f
getAuditRecords(f)
However, it looks like there's a timestamp attached to each filename. If /mnt/hcp1/R1P/R1P_ora_982_2.xml.201409070400 means that the file was created on 7 September 2014 at 04:00 (and if the timezones, etc. aren't an issue), you may want to consider parsing those strings instead of statting the file.
And once you're parsing date strings, you might as well use the simpler and higher-level datetime library instead of the lower-level time. (You could do this with the previous version too, but since getmtime returns a time-style timestamp, you'd have to convert it manually to use it as a datetime, so there's less advantage.)
So:
def fileCreation(path):
now = datetime.datetime.now()
oneday_ago = now - datetime.timedelta(days=1)
fileext = os.path.splitext(path)[1][1:]
filetime = datetime.datetime.strptime(fileext, '%Y%m%d%H%M')
if filetime < oneday_ago:
print f
getAuditRecords(f)
(Also, I'm not sure what that f is. Maybe you meant path?)
Regarding the "two days ago" part, you should use datetime.datetime and datetime.timedelta
E.g.
import datetime
now = datetime.datetime.now()
two_days = datetime.timedelta(days=2)
two_days_ago = now - two_days

Categories

Resources