from datetime import datetime
now = datetime.now()
sentence = "{:%B %d %Y}".format(now=datetime.now)
If for some reason I have to use an import from keyword how would I format this in three lines like the example above? My exact question is I don't know how to use the format parameters in this case.
You need pass datetime.now(), not datetime.now method itself.
specify now in the format string to use the keyword argument. Or you can omit now if you pass the datetime object as a positional argument.
>>> from datetime import datetime
>>> now = datetime.now()
>>> "{now:%B %d %Y}".format(now=datetime.now()) # keyword argument
'November 12 2016'
>>> "{:%B %d %Y}".format(datetime.now()) # positional argument
'November 12 2016'
>>> "{0:%B %d %Y}".format(datetime.now()) # positional argument + explicit 0 (first arg)
'November 12 2016'
as furas commented above, this works:
>>> from datetime import datetime
>>> sentence = datetime.now().strftime("%B %d %Y")
>>> print sentence
November 12 2016
>>>
Related
i try to get obj but i can't please any solution thank you !
def check_date(get_date):
date_obj = datetime.datetime.strptime('08-déc-2022 09:02','%d-%b-%y %H:%M')
print('date object formta',date_obj)
One thing I've noticed is that you need to use %Y as it stands for the 4 digits notation of a year (2022), where %y is just 2 digits (22)
Another thing, the Month abbreviation has to start with an uppercase letter (Déc)
Also, it really depends on your locale, as in mine, I couldn't use Déc and had to use Dec
You can check your locale via:
import locale
locale.getlocale()
I tried to be smart and create a one liner which can extract the datetime of my_string and make a datetime of it. However, it did not work quiet well.
my_string = 'London_XX65TR_20211116_112413.txt'
This is my code:
datetime= datetime.datetime.strptime(my_string .split('_')[2],'%Y%m%d_%H%M%S')
This is my output:
ValueError: time data '20211116' does not match format '%Y%m%d_%H%M%S'
You could use the maxsplit argument in str.split:
>>> from datetime import datetime
>>> region, code, date_time = my_string[:-4].split('_', maxsplit=2)
>>> datetime.strptime(date_time, "%Y%m%d_%H%M%S")
datetime.datetime(2021, 11, 16, 11, 24, 13)
Which means only split at, at most maxsplit occurrences of the _ characters from the left, leave the rest as is.
For this particular case, instead of my_string[:-4], you could use my_string.rstrip('.txt'), it is not advised in general, because it may strip some useful information as well. Whereas, from Python 3.9+ you could use str.removesuffix:
>>> my_string = 'London_XX65TR_20211116_112413.txt'
>>> region, code, date_time = my_string.removesuffix('.txt').split('_', maxsplit=2)
>>> datetime.strptime(date_time, "%Y%m%d_%H%M%S")
datetime.datetime(2021, 11, 16, 11, 24, 13)
You could use re.findall here:
from datetime import datetime
my_string = 'London_XX65TR_20211116_112413.txt'
ts = re.findall(r'_(\d{8}_\d{6})\.', my_string)[0]
dt = datetime.strptime(ts, '%Y%m%d_%H%M%S')
print(dt) # 2021-11-16 11:24:13
This approach uses a regex to extract the timestamp from the input string. The rest of your logic was already correct.
The Method you are following is correct. It's just you are not considering the HH:MIN:Sec part and need to append that before formatting,
my_string = 'London_XX65TR_20211116_112413.txt'
my_date = (my_string .split('_')[2]+my_string .split('_')[3]).replace(".txt","")
datetime= datetime.datetime.strptime(my_date,'%Y%m%d%H%M%S')
print(datetime) # 2021-11-16 11:24:13
Your code does not work because my_string .split('_') gives ['London', 'XX65TR', '20211116', '112413.txt'] so in strptime('20211116', '%Y%m%d_%H%M%S') return an error.
You should either :
limit the format to `'%Y%m%d', loosing the HMS
find another way to get the whole substring matching the format
The first part of the alternative is trivial so lets go for the second one using regex.
import regex as re
datetime = datetime.datetime.strptime(re.search(r'\d{8}_\d{6}', my_string)[0],'%Y%m%d_%H%M%S')
from datetime import datetime
date_time_str = '18/09/19 01:55:19'
date_time_obj = datetime.strptime(date_time_str, '%d/%m/%y %H:%M:%S')
print ("The type of the date is now", type(date_time_obj))
print ("The date is", date_time_obj)
I currently have a datetime object with time that looks like 06:00:00 and am trying to convert it to a string that looks like "6:00 am".
I have been trying to use the Python Strftime libraries but am having trouble, could someone point me in the right direction? Thanks :)
You should just be able to use %I:%M %p, as per the following transcript:
>>> import datetime
>>> now = datetime.datetime.now()
>>> now
datetime.datetime(2020, 3, 30, 14, 6, 49, 62354)
>>> print(now.strftime("%I:%M %p"))
02:06 PM
See here for a list of the different format codes.
If, as your question implies, you need it without a leading zero on the hour, and in lower-case, you can just use regular expressions for the former and lower() for the latter:
>>> import re
>>> print(re.sub("^0", "", now.strftime("%I:%M %p")).lower())
2:06 pm
This works for me:
>>> import datetime
>>> datetime.datetime.now().strftime( '%H:%M %p' )
'15:09 PM'
I have a string like this:
>>> string = "bla_bla-whatever_2018.02.09_11.34.09_more_bla-123"
I need to extract the date 2018.02.09_11.34.09 from it. It will always be in this format.
So I tried:
>>> match = re.search(r'\d{4}\.\d{2}\.\d{2}_\d{2}\.\d{2}\.\d{2}', string)
It correctly extracts out the date from that string:
>>> match.group()
'2018.02.09_11.34.09'
But then when I try to create a datetime object from this string, it doesn't work:
>>> datetime.datetime.strptime(match.group(), '%Y.%m.%d_%H.%I.%S')
ValueError: time data '2018.02.09_11.34.09' does not match format '%Y.%m.%d_%H.%I.%S'
What am I doing wrong?
You need to replace the format specifier %I with %M, for minutes:
%Y.%m.%d_%H.%M.%S
%I denotes hour in 12-hour format so from (0)1..12, whereas based on your example, you have 34 as the value, which presumably is in minutes (%M).
My input to this is in the format 07:05:09PM
expected output:
19:05:09
output got:
19:5:9
def timeConversion(s):
if "AM" in s:
print(s[1:8])
else:
string=s.split(':')
print(string)
string.append(string[2][0:2])
string.remove(string[2])
print(string)
date=list(map(int, string))
print(date)
a=date[0]+12
b='%s:%s:%s' % (a, date[1], date[2])
return b
My question is when I convert the date from string to int using map the zero is not picked up, is there any way to get the integer as such???
If you don't want to use a custom function for formatting datetimes, you can get the intended output by formatting your string when you print it. Replace this line
b='%s:%s:%s' % (a, date[1], date[2])
with this:
b='%02d:%02d:%02d' % (a, date[1], date[2])
there are functions for converting 24h to 12h time :
Load the string into a datetime object via strptime(), then dump via strftime() in the desired format:
from datetime import datetime
d = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
d # d is a string '2016-04-28 07:46:32'
datetime.strptime(d, "%Y-%m-%d %H:%M:%S").strftime("%Y-%m-%d %I:%M:%S %p")
'2016-04-28 07:46:32 AM'
Note that the %I here is a 12-hour clock
Conversion of 24 hours date/time to 12 hours format and vice-versa
if you want to use your solution you can add leading zeros to integrs like in How to add Trailing zeroes to an integer :
numbers = [1, 19, 255]
numbers = [int('{:<03}'.format(number)) for number in numbers]
you can print leading zeros like in Display number with leading zeros