I'm trying to get make a comments section for a website with the backend written in python. As of now, everything works fine except I cannot figure out how to format the date and time the way I want.
What I am trying to have at the time of posting is either of these:
Posted on Tue, 06/12/18 at - 11:20
or
Posted on 06/12/18 at - 11:21
Currently, what I have when the method is called is this:
import time
from datetime import *
time = ("Posted on " + str(datetime.now().day) + "/"
+ str(datetime.now().month) + " at: " + str(datetime.now().hour)
+ ":" + str(datetime.now().minute))
You can use datetime.datetime.strftime() to build any format you want:
import datetime
time = datetime.datetime.now().strftime("Posted on %d/%m/%y at - %H:%M")
print(time) # Posted on 07/12/17 at - 00:29
Read up more on special classes you can use when building your date: strftime() and strptime() Behavior
datetime.datetime.now().strftime('%d/%m/%y at - %H:%M')
'06/12/17 at - 16:29'
Related
Is this not allowed or did I type something wrong?
import datetime
print(f"Current Time: {datetime.datetime.now().strftime("%I:%M:%S %p")}"
Syntax error at %I:%M...
^
You are ending your fstring by using double quotes in your strftime() function, use single quotes or escape them.
For example:
print(f"Current Time: {datetime.datetime.now().strftime('%I:%M:%S %p')}"
Also, not related to your question, but you are not really using fstrings in the right way.
It would look a lot nicer if you defined a 'current time' variable and then put it in your fstring.
For example:
current_time = datetime.datetime.now().strftime('%I:%M:%S %p')
print(f"Current Time: { current_time }")
Why not like this:
from datetime import datetime
print(f'Current Time: {datetime.now():%I:%M:%S %p}')
See PEP498.
print(f'Current Time: {datetime.datetime.now().strftime("%I:%M:%S %p")}')
Quotes bro.
The datetime class already has a pre-configured date to string method : strftime()
So your code can look something like this :
import datetime
date_today = datetime.datetime.now()
date_today.strftime('%I:%M:%S %p')
Its because of quotes. Here is workaround method and your original method.
import datetime
print (f'Current Time : {datetime.datetime.now().strftime("%I:%M:%S %p")}')
import datetime
d = datetime.datetime.now().strftime("%I:%M:%S %p")
print(f"Current Time: {d}")
everyone! I'm having some trouble in matching two strings.
So, I've got this HTML code from a page I'm testing:
<td class="fixedColumn ng-binding"
ng-style="{'padding':'5px','line-height':'10px'}" style="padding: 5px; line-height: 10px;">
(today's date: 2016-09-23)
</td>
The actual string that's displayed in the page is (today's date: 2016-09-23).
What I tried to do using Python is this:
#check if today's date = current date
currentDate = datetime.date.today().strftime("(today's date: %Y-%m-%d)")
todayDate = driver.find_element_by_xpath("//td[contains(text(), 'currentDate']")
allOk = 'all good!'
notOk = 'still not OK...'
if todayDate == currentDate:
print(allOk)
home = driver.find_element_by_xpath("//a[#title='Home']").click()
else:
print(notOk)
driver.close()
What happens when I run the script is, obviously, that the browser closes, according to driver.close() , but I need the shell to print 'all good!' in the shell and for the browser to go to "Home" by "clicking".
I'm really new to Python, but as far as I'm concerned, I did everything possible to make this work. Could anyone give me some hints and point out to what I'm missing? Thank you :)
todayDate = driver.find_element_by_xpath("//td[contains(text(), 'currentDate']")
The quotes around currentDate are making the XPath refer to something that contains the actual text 'currentDate', not the text that the currentDate variable refers to, you need to change it to this:
todayDate = driver.find_element_by_xpath("//td[contains(text(), " + currentDate + "]")
you may also need to wrap currentDate in str(currentDate) to make sure it casts as a string, that was a problem I once faced.
'+' in python concatenates strings together, so this should make it look for the text that variable refers to. Hope this fixes it for you!
Another method that does not use a python variable as suggested by Jon Clements:
You can make this clearer by using string formatting instead, eg:
"//td[contains(text(), {})]".format(date.today())
just make sure there's a from datetime import date before hand...
Ok, so it's been about 10 minutes since I've added a comment, but I've made it work.
Code before:
todayDate = driver.find_element_by_xpath("//td[contains(text(),
" + str(currentDate) + ")]")
Code after:
todayDate = driver.find_element_by_xpath("//td[contains(text(),
'" + str(currentDate) + "')]")
I put " + str(currentDate) + " in '' . Also, I changed
`if todayDate == currentDate:` to `if todayDate:`
It works as intended now, I only need to figure out why :) anyway, thank you AntlerFox and Jon Clements for your trouble.
i'm a python beginner and having an issue. Trying to pull API info and convert the extracted JSON time object to a datetime object in Python so I can run the date.weekday() function on it eventually (the overall goal is to extract all the dates from the API and see which the output by days - I plan on populating a empty dictionary once I can extract all the dates).
For some reason, even with my conditional statements, I'm still printing (2015, 04, 06) with all the zeroes. That's my problem.
I have a feeling I'm getting something basic wrong, and that there's also a better way to go about this than doing all the ifs/elses with the 0-padding in the date object.
here's my code so far:
from datetime import date
import datetime
import json
import requests
r = requests.get('https://api.github.com/repos/mbostock/d3/commits?since=2015-04-12330:00:000')
jsonoutput = r.json()
modified = (jsonoutput[0]["commit"]["author"]["date"])
#at this point, modified gives something like: "2015-04-06T22:28:16Z"
if modified[5] == 0:
if modified[8] == 0:
new_format = ("(" + modified[0:4] + ", " + modified[6] + ", " + modified[9] + ")")
#with the particular jsonoutput[0] pulled here, this one should be triggered
else:
new_format = ("(" + modified[0:4] + ", " + modified[6] + ", " + modified[8:10] + ")")
else:
if modified[8] == 0:
new_format = ("(" + modified[0:4] + ", " + modified[5:7] + ", " + modified[9] + ")")
else:
new_format = ("(" + modified[0:4] + ", " + modified[5:7] + ", " + modified[8:10] + ")")
print(new_format)
print(date.weekday(datetime.date(new_format)))
The error happens in your current code because new_format is defined as a string, while the datetime.date takes the arguments as integers. Also, since you compare the string "0" with the numerical 0, the modified is simply not created.
Instead of this:
new_format = ("(" + modified[0:4] + ", " + modified[6] + ", " + modified[8:10]) + ")")
do this:
new_format = (int(modified[0:4]), int(modified[5:7]), int(modified[8:10]))
The above will work with all of your cases, so you can remove the convoluted if-else blocks as well.
Alternatively, you could split this modeified string by "T", and then use another split by "-" to get the integer values:
new_format = map(int, modified.split("T")[0].split("-"))
You'll also need to unpack the list when passing as the argument, so your complete code becomes:
import json
import requests
from datetime import date
r = requests.get('https://api.github.com/repos/mbostock/d3/commits?since=2015-04-12330:00:000')
jsonoutput = r.json()
modified = jsonoutput[0]["commit"]["author"]["date"]
new_format = (int(modified[0:4]), int(modified[5:7]), int(modified[8:10]))
print(date.weekday(date(*new_format)))
Also, as others have already pointed out in their answers, it might be a better idea to dateutil.parser.parse than to write your own parsing logic. (dateutil is not a builtin package, you'll have to install it) :)
What you get from the json is actually a datetime representation in an ISO format
You can refer to this SO answer https://stackoverflow.com/a/15228038/58129 to convert the string
You're trying to make your own parsing functions where Python has its own.
from dateutil import parser
from datetime import date
my_date = dateutil.parser.parse(modified)
is_week_day = date.weekday(my_date)
If dateutil is not installed on your machine, try pip install python-dateutil
However, if you want to go with Python's standard library:
from datetime import date, datetime
from time import strptime
mytime = strptime(modified, '%Y-%m-%dT%H:%M:%SZ')
my_date = datetime(*my_time[:6])
is_week_day = date.weekday(my_date)
I need a function to generate datafile names with a suffix which must be the current date and time.
I want for the date Feb, 18 2014 15:02 something like this:
data_201402181502.txt
But this is that I get: data_2014218152.txt
My code...
import time
prefix_file = 'data'
tempus = time.localtime(time.time())
suffix = str(tempus.tm_year)+str(tempus.tm_mon)+str(tempus.tm_mday)+
str(tempus.tm_hour)+str(tempus.tm_min)
name_file = prefix_file + '_' + suffix + '.txt'
You can use time.strftime for this, which handles padding leading zeros e.g. on the month:
from time import strftime
name_file = "{0}_{1}.txt".format(prefix_file,
strftime("%Y%m%d%H%M"))
If you simply turn an integer to a string using str, it will not have the leading zero: str(2) == '2'. You can, however, specify this using the str.format syntax: "{0:02d}".format(2) == '02'.
Looks like you want
date.strftime(format)
The format string will allow you to control the output of strftime, try something like:
"%b-%d-%y"
From http://docs.python.org/2/library/datetime.html
Using str.format with datetime.datetime object:
>>> import datetime
>>> '{}_{:%Y%m%d%H%M}.txt'.format('filename', datetime.datetime.now())
'filename_201402182313.txt'
In Python v2, is there a way to get a date/time stamp and put it into creating a new text file?
IE: When I want to create a new text file and write the contents of my program to it, it will create a new text file with the time/date in it.
Thanks for any help.
import datetime
def timeStamped(fname, fmt='%Y-%m-%d-%H-%M-%S_{fname}'):
return datetime.datetime.now().strftime(fmt).format(fname=fname)
with open(timeStamped('myfile.txt'),'w') as outf:
outf.write('data!')
This will prepend a timestamp to the front of the filename:
from datetime import datetime
# define a timestamp format you like
FORMAT = '%Y%m%d%H%M%S'
path = 'foo.txt'
data = 'data to be written to the file\n'
new_path = '%s_%s' % (datetime.now().strftime(FORMAT), path)
open(new_path, 'w').write(data)
import datetime
f=open("/home/rohitsai/Documents/acs.txt",'a')
f.write ("heloo"+'\t')
f.write(datetime.datetime.now().ctime())
print datetime.datetime.now()
this code will add helo as well as current date on same file. 'a' is for append mode, \t for tab space.
import datetime
open("file", "w").write(datetime.datetime.now().ctime())
open(datetime.datetime.now().ctime(), "w").write("foo")
I like just having the date in my file handles:
from datetime import date
def timeIzNow():
'''
returns current date as a string
'''
now = date.today()
full = "-" + str(now.month) + "-" + str(now.day) + "-" + str(now.year)
return full
fileN = "findGenes"
with open(fileN + timeIzNow() + ".txt", 'w') as f:
#DO STUFF
Your new file name will look like
findGenes-6-5-2013.txt
A lot of these answers are unnecessarily complicated if you just want to spit out a timestamp to a file and don't care about tweaking the format of said stamp
You can literally do it in one line:
f.write(datetime.now().__str__() + "\n")
Here I assume f is a file - so we print the string representation of datetime.now() and add a new line, because write() doesn't do that for you. (You probably already knew that though.)
Note: checked working with Python 3, I didn't test with Python 2, I'm not sure which version of the language spec you are using.