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
Related
I have a .txt file that contains the string "2020-08-13T20:41:15.4227628Z"
What format code should I use in strptime function in Python 3.7? I tried the following but the '8' at end just before 'Z' is not a valid weekday
from datetime import datetime
timestamp_str = "2020-08-13T20:41:15.4227628Z"
timestamp = datetime.strptime(timestamp_str, '%Y-%m-%dT%H:%M:%S.%f%uZ')
ValueError: time data '2020-08-13T20:41:15.4227628Z' does not match format '%Y-%m-%dT%H:%M:%S.%f%uZ'
your timestamp's format is mostly in accordance with ISO 8601, except for the 7 digit fractional seconds.
The 7th digit would be 1/10th of a microsecond; normally you'd have 3, 6 or 9 digits resolution (milli-, micro or nanoseconds respectively).
The Z denotes UTC
In Python, you can parse this format conveniently as I show here.
The 7 digits following the . appear to be a number of nanoseconds. You may have a platform-specific format (defined by strftime(3)) available to use in place of %f, but if not, your best bet is to drop the trailing digit before attempting to parse the remaining string as a timestamp.
regex = "(\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{6}).(\d.*)"
if (m := re.match(regex, timestamp_str) is not None:
timestamp_str = "".join(m.groups())
timestamp = datetime.strptime(timestamp_str, '%Y-%m-%dT%H:%M:%S.%fZ')
This question already has answers here:
Python converting letter to two-digit number
(2 answers)
Closed 1 year ago.
I am trying to convert the date format '31-Dec-09' to '2009-12-31' in Python with the following code:
df = ['19-Jan-19', '4-Jan-19']
f = [datetime.datetime.strptime(x,'%d-%mmm-%y').strftime('%Y-%m-%d') for x in df]
print(f)
Getting the following error:
time data '9-Jan-19' does not match format '%d-%mmm-%y'
I have read somewhere that matching a two-digit year '00' would require a lowercase y instead of an upper case one. Either way, I am getting the same error so I guess something else is wrong. Any help?
Your %y and %Y patterns are fine, the issue is that you used %mmm here. The datetime.strptime() method patterns are all single letter patterns, and %mmm is seen as the %m pattern followed by two literal m characters. %m matches a numeric month (1 or 2 digits, zero-padding optional). So 19-1mm-19 would match, but 19-Jan-19 does not because the month is not numeric and the two literal m characters are missing.
The correct pattern to use is '%d-%b-%y' here, where %b matches an abbreviated month name.
Demo:
>>> import datetime
>>> df = ['19-Jan-19', '4-Jan-19']
>>> [datetime.datetime.strptime(x,'%d-%b-%y').strftime('%Y-%m-%d') for x in df]
['2019-01-19', '2019-01-04']
Since you're specifying month in short hand notation, you should use %b instead of %mmm (That is not a valid format in datetime)
Is there a quick way to truncate the microsecond part, down to 6 digits in an iso date-time string?
For example if the input is:
date = '2019-01-09T15:26:23.623349123+01:00'
I'd like output to be:
date = '2019-01-09T15:26:23.623349+01:00'
I have done this using string.index() but resulting code is quite ugly.
This will do
from dateutil import parser
k = parser.parse('2019-01-09T15:26:23.623349123+01:00').isoformat()
print(k)
You can do it with simple string operations.
If the length is greater than 32, you want to keep the 26 first characters and the 6 last ones.
In Python if gives:
def reformat(dat):
if len(dat) > 32:
return dat[:26] + dat[-6:]
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).
Hi i have written regex to check where ther string have the char like - or . or / or : or AM or PM or space .The follworig regex work for that but i want to make case fail if the string contain the char other than AMP .
import re
Datere = re.compile("[-./\:?AMP ]+")
FD = { 'Date' : lambda date : bool(re.search(Datere,date)),}
def Validate(date):
for k,v in date.iteritems():
print k,v
print FD.get(k)(v)
Output:
Validate({'Date':'12/12/2010'})
Date 12/12/2010
True
Validate({'Date':'12/12/2010 12:30 AM'})
Date 12/12/2010
True
Validate({'Date':'12/12/2010 ZZ'})
Date 12/12/2010
True (Expecting False)
Edited:
Validate({'Date':'12122010'})
Date 12122010
False (Expecting False)
How could i find the string have other than the char APM any suggestion.Thanks a lot.
Give this a try:
^[-./\:?AMP \d]*$
The changes to your regex are
It's anchored with ^ and $ which means that the whole line should match and not partially
the \d is added to the character class to allow digits
Now the regex basically reads as list of symbols that are allowed on 1 lines
If you want the empty string not to match then change the * to a +
You could use an expression like this instead:
^[-0-9./:AMP ]+$
^ and $ anchor the expression at the beginning and end of string, making sure there is nothing else in it (except an optional new line after $).
The way you approach this is too naive to deal with garbled input like '-30/A-MP/2012/12', '-30/A-MP/20PA12/12'.
If you want to validate your dates robustly, how about:
import datetime
date = '12-12-2012 10:45 AM'
formats = ("%d-%m-%Y %I:%M %p", "%d/%m/%Y %I:%M %p", ...)
for fmt in formats:
try:
valid_date = datetime.datetime.strptime(date, fmt)
except ValueError as e:
print(e)
You would have to define all possible formats, but you will get full datetime objects (or time or date objects, they work similar), and you can be absolutely sure they are valid. For a full explanation of the available format specifiers: http://docs.python.org/library/time.html#time.strftime
Kind of elaborate, but does the trick.
import re
Datere = re.compile("""
^(?:\d\d[-./\:]){2} ## dd_SEP_dd
\d{4}\s* ## year may be followed by spaces
(?:\d\d[-./\:]\d\d\s+(?:AM|PM))? ## hh_SEP_mm spaces followed by AM/PM and this is optional
\s*$""",re.X)
FD = { 'Date' : lambda date : bool(re.search(Datere,date)),}
def Validate(date):
for k,v in date.iteritems():
print k,v
print FD.get(k)(v)
print Validate({'Date':'12/12/2010'})
print Validate({'Date':'12/12/2010 12:30 AM'})
print Validate({'Date':'12/12/2010 ZZ'})