Python formatted strings and datetime - python

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}")

Related

How to convert a downloaded string to datetime format?

I am trying to check if today's date < date downloaded from text file online. Here is my code :
import datetime
import requests
URL = "http://directlinktotextfile.com/text.txt"
result = requests.get(URL)
today = datetime.datetime.now().date()
Url_date = result.text
Url_date.strip()
Url_date = datetime.date(Url_date)
if today < Url_date :
print "Today is less than future date"
raw_input()
else:
print "Today is greater than or = to future date"
raw_input()
The result that comes back is just this : 2018,02,14. I use .strip() in case there might be blank spaces or extra lines. I've printed out result.text after strip() and it shows the correct details. Why is it that I can't check if today < Url_date. It works fine if I enter manually a date into datetime.date(2018,02,14), but when I'm downloading the string it won't work. Any suggestions?
You pass string to datetime.date() which should be each an integer.
Url_list = []
Url_list = Url_date.split(",")
yr = int(Url_list[0])
mn = int(Url_list[1])
d = int(Url_list[2])
Now pass these integers to datetime.date
Url_date = datetime.date(yr, mn, d)
The arguments you pass to datetime.date(arg1, arg2, arg3) are not strings as a whole. When you pass it from url, what you are actually doing is
datetime.date("2018,2,14")
Note that you are passing only one string argument and not 3 different integers. You should split the date string using comma and then convert each into integers and then pass them as arguments to datetime.date.
Here is what your code is trying to do :
Url_date = datetime.date("2018,02,14")
But he wants to have:
Url_date = datetime.date(2018,02,14)
Do
Url_date.split(',') # Result: ['2018','02','14']
And then convert all the string in the array in integers
It should be ok :)
Use strptime:
import datetime
today = datetime.datetime.now().date()
parsed = datetime.datetime.strptime("2018,02,14", "%Y,%m,%d").date()
print(today < parsed) # True

How to format dates and times?

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'

How to remove T from time format %Y-%m-%dT%H:%M:%S?

How to remove T from time format %Y-%m-%dT%H:%M:%S in python?
Am using it in my html as
<b>Start:{{ start.date_start }}<br/>
Manually format the datetime, don't rely on the default str() formatting. You can use datetime.datetime.isoformat() for example, passing in a space as the separator:
<b>Start:{{ start.date_start.isoformat(' ') }}<br/>
or you can use datetime.datetime.strftime() to control formatting more finely:
<b>Start:{{ start.date_start.strftime('%Y-%m-%d %H:%M:%S') }}<br/>
#register.filter
def isotime(datestring):
datestring = str(datestring)
return datestring.replace("T"," ")

How get a datetime string to suffix my filenames?

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'

Add utc time to filename python

How can i get the current time in UTC time (Zulu style for hours and minutes: 0100Z) , and add it to a string so i can concatenate it
This gives me cannot concatenate string:
import datetime
utc_datetime = datetime.datetime.utcnow()
utc_datetime.strftime("%Y-%m-%d-%H%MZ") //Result: '2011-12-12-0939Z'
filename = '/SomeDirectory/AnotherDirectory/FilePrefix_'+utc_datetime+'.txt'
And this gives me another string for the filename:
//returns: /SomeDirectory/AnotherDirectory/FilePrefix_2011-12-12 09:42:15.374022.txt
import datetime
utc_datetime = datetime.datetime.utcnow()
utc_datetime.strftime("%Y-%m-%d-%H%MZ") //Result: '2011-12-12-0939Z'
filename = '/SomeDirectory/AnotherDirectory/FilePrefix_'+str(utc_datetime)+'.txt'
Thanks in advance
What you want to do is probably :
import datetime
utc_datetime = datetime.datetime.utcnow()
formated_string = utc_datetime.strftime("%Y-%m-%d-%H%MZ") //Result: '2011-12-12-0939Z'
filename = '/SomeDirectory/AnotherDirectory/FilePrefix_%s.txt'% formated_string
or in a one-liner way :
filename = '/SomeDirectory/AnotherDirectory/FilePrefix_%s.txt'%datetime.datetime.utcnow().strftime("%Y-%m-%d-%H%MZ")
When using datetime.strftime it returns the string formatted as you need, it does not modify the datetime object.
EDIT : use %s instead of +, thanks Danilo Bargen
The strftime method of a datetime object only returns a value, but doesn't manipulate the original object. You need to save the result into the variable itself, or into a new variable.
import datetime
utc_datetime = datetime.datetime.utcnow().strftime("%Y-%m-%d-%H%MZ")
utc_datetime //Result: '2011-12-12-0939Z'
Additionally, you shouldn't use + to concatenate several strings because of performance reasons. Use this instead:
filename = '/directory/prefix_%s.txt' % utc_datetime
You need to save the result of utc_datetime.strftime() into a variable:
>>> import datetime
>>> utc_datetime = datetime.datetime.utcnow()
>>> s=utc_datetime.strftime("%Y-%m-%d-%H%MZ")
>>> filename = '/SomeDirectory/AnotherDirectory/FilePrefix_' + s + '.txt'
>>> print filename
/SomeDirectory/AnotherDirectory/FilePrefix_2011-12-12-0946Z.txt
>>>
You're currently computing a value and throwing away the string result.

Categories