I am very new in python working on dates. I have 2 type of dates (because getting in array dynamically). Something like this ['2022-02-17 08:29:36.345374' , '2021-03-18 08:29:36']
I am trying to get these in this format 17/02/2022 08:29 PM.
Until now trying something like this:
def update_date(datetime):
date_formating = datetime.strptime(date_time, '%m/%d/%Y %I:%M %p')
return date_formating
but getting errors like:
ValueError: time data '2022-02-17 08:29:36.345374' does not match format '%m/%d/%Y %I:%M %p'
I need a solution which can turn both formats I am getting into desired format. Any help would be highly appreciated.
Try a list comprehension with datetime.fromisoformat(date_string):
>>> from datetime import datetime
>>> date_strs = ['2022-02-17 08:29:36.345374', '2021-03-18 08:29:36']
>>> [datetime.fromisoformat(s).strftime('%d/%m/%Y %I:%M %p') for s in date_strs]
['17/02/2022 08:29 AM', '18/03/2021 08:29 AM']
The times in the given list come in two different formats
with microseconds
with seconds (and no microseconds)
This code highlights the differences and would work:
import datetime as dt
t = ['2022-02-17 08:29:36.345374' , '2021-03-18 08:29:36']
# format with microseconds
d1 = dt.datetime.strptime(t[0], '%Y-%m-%d %H:%M:%S.%f')
# format with seconds
d2 = dt.datetime.strptime(t[1], '%Y-%m-%d %H:%M:%S')
# format user wants
x = d1.strftime('%m/%d/%Y %I:%M %p')
y = d2.strftime('%m/%d/%Y %I:%M %p')
print(x)
print(y)
The result:
02/17/2022 08:29 AM
03/18/2021 08:29 AM
Related
I want to covert a string item to the datetime format that I require.
The string item is this : '3/27/2013 2:54:00 PM'
My code is as follows: map(datetime.datetime.strptime,'3/27/2013 2:54:00 PM', '%m/%d/%Y %I:%M:%S %p')
I get the following error : stray % in format '%'
Any help is appreciated.
Not sure why you use map, you can just use strptime on that string, worked for me
import datetime
dt = datetime.datetime.strptime('3/27/2013 2:54:00 PM', '%m/%d/%Y %I:%M:%S %p')
print(dt)
I am trying to parse the string '10/23/2019 6:02:05 PM EST' into a datetime with time zone using Python 3.7.
Code:
from datetime import datetime
timestamp = datetime.strptime(date_str, '%m/%d/%Y %I:%M:%S %p %Z')
Error:
ValueError: time data '10/23/2019 6:02:05 PM EST' does not match format '%m/%d/%Y %I:%M:%S %p %Z'
When I create a datetime and output it using the same formatting I get the correct output. The only difference is that there is a 0 in front of the hour, but adding 0 in front of the 6 in my date string results in the same error.
My current solution is to parse the datetime without the timezone and then localize it, but this is not ideal.
date_lst = date.split()
date_str = ' '.join(date_lst[0:3])
timestamp = datetime.strptime(date_str, '%m/%d/%Y %I:%M:%S %p')
new_tz = pytz.timezone(date_lst[3])
timestamp_tz = new_tz.localize(timestamp)```
It is reasonable to expect that parsing a string with a timezone included would produce a timezone aware datetime object.
Try it
>>timestamp = datetime.strptime('10/23/2019 6:02:05 PM EST', '%m/%d/%Y %I:%M:%S %p EST')
>>2019-10-23 06:02:05
You can try this.
I've a string in the following date/time format:
2018-05-20T07:06:23.226
I need to convert it to the following format:
2018-05-20 06:23 AM
I tried the following code, but I'm surely making some mistake here:
date = "2018-05-20T07:06:23.226"
d = datetime.datetime.strptime('date', '%Y-%m-%dT%H:%M:%S.%f')
new_date = d.strftime('%y-%m-%d %H:%M %p')
I always get the following error:
ValueError: time data 'date' does not match format '%Y-%m-%dT%H:%M:%S.%f'
replace:
d = datetime.datetime.strptime('date', '%Y-%m-%dT%H:%M:%S.%f')
with
d = datetime.datetime.strptime(date, '%Y-%m-%dT%H:%M:%S.%f')
Also
new_date = d.strftime('%y-%m-%d %H:%M %p')
with
new_date = d.strftime('%Y-%m-%d %I:%M %p')
If you wish to use variable inside string, you can do it since Python 3.6:
date = "2018-05-20T07:06:23.226"
d = datetime.datetime.strptime(f'{date}', '%Y-%m-%dT%H:%M:%S.%f')
new_date = d.strftime('%y-%m-%d %H:%M %p')
I'm using python 3.5.
I have a string formatted as mm/dd/yyyy H:MM:SS AM/PM that I would like as a python datetime object.
Here is what I've tried.
date = "09/10/2015 6:17:09 PM"
date_obj = datetime.datetime.strptime(date, '%d/%m/%Y %I:%M:%S %p')
But this gets an error because the hour is not zero padded. The formatting was done per the table on the
datetime documentation, which does not allow the hour to have one digit.
I've tried splitting the date up, adding a zero and then reassembling the string back together, while this works, this seems less robust/ideal.
date = "09/10/2015 6:17:09 PM"
date = date.split()
date = date[0] + " 0" + date[1] + " " + date[2]
Any recommendation on how to get the datetime object directly, or a better method for padding the hour would be helpful.
Thank you.
There is nothing wrong with this code:
>>> date = "09/10/2015 6:17:09 PM"
>>> date_obj = datetime.datetime.strptime(date, '%m/%d/%Y %I:%M:%S %p')
>>> date_obj
datetime.datetime(2015, 9, 10, 18, 17, 9)
>>> print(date_obj)
2015-09-10 18:17:09
The individual attributes of the datetime object are integers, not strings, and the internal representation uses 24hr values for the hour.
Note that I have swapped the day and month in the format strings as you state that the input format is mm/dd/yyyy.
But it seems that you actually want it as a string with zero padded hour, so you can use datetime.strftime() like this:
>>> date_str = date_obj.strftime('%m/%d/%Y %I:%M:%S %p')
>>> print(date_str)
09/10/2015 06:17:09 PM
# or, if you actually want the output format as %d/%m/%Y....
>>> print(date_obj.strftime('%d/%m/%Y %I:%M:%S %p'))
10/09/2015 06:17:09 PM
This question already has answers here:
Convert 12-hour date/time to 24-hour date/time
(8 answers)
Convert string "Jun 1 2005 1:33PM" into datetime
(26 answers)
Closed 7 years ago.
I have a string containing time stamp in format
(DD/MM/YYYY HH:MM:SS AM/PM), e.g."12/20/2014 15:25:05 pm"
.
The time here is in 24 Hrs format.
I need to convert into same format but with time in 12-Hrs format.
I am using python version 2.6.
I have gone through time library of python but couldn't come up with any solution.
View Live ideOne use Python datetime,
>>> from datetime import datetime as dt
>>> date_str='12/20/2014 15:25:05 pm'
>>> date_obj = dt.strptime(date_str, '%m/%d/%Y %H:%M:%S %p')
>>> dt.strftime(date_obj, '%m/%d/%Y %I:%M:%S %p')
'12/20/2014 03:25:05 PM'
The trick is to convert your Input date string to Python datetime object and then convert it back to date string
import datetime
#Input Date String
t = "12/20/2014 15:25:05 pm"
#Return a datetime corresponding to date string
dateTimeObject = datetime.datetime.strptime(t, '%m/%d/%Y %H:%M:%S %p')
print dateTimeObject
Output: 2014-12-20 15:25:05
#Return a string representing the date
dateTimeString = datetime.datetime.strftime(dateTimeObject, '%m/%d/%Y %I:%M:%S %p')
print dateTimeString
Output: 12/20/2014 03:25:05 PM
After creating a datetime object using strptime you then call strftime and pass the desired format as a string see the docs:
In [162]:
t = "12/20/2014 15:25:05 pm"
dt.datetime.strftime(dt.datetime.strptime(t, '%m/%d/%Y %H:%M:%S %p'), '%m/%d/%Y %I:%M:%S %p')
Out[162]:
'12/20/2014 03:25:05 PM'
Shortest & simplest solution --
I really appreciate & admire (coz I barely manage to read man pages :P) you going through time documentation, but why use "astonishing" & "cryptic" code when simple code could get the job done
Just extract the hour part as int & replace it by hrs-12 if it is greater than 12
t = "12/20/2014 15:25:05 pm"
hrs = int( t.split()[1][:2] )
if hrs > 12:
t = t.replace( str(hrs), str(hrs-12) )
Output
See explaination & live output here
Using Lambda
If you like one liners, checkout f() below
t = "12/20/2014 15:25:05 pm"
f = lambda tym: tym.replace(str(int(tym.split()[1][:2])), str(int(tym.split()[1][:2])-12)) if int(tym.split()[1][:2]) > 12 else tym
print(f(t))