I have the following Datetime string: Dec 03 2020 01: +0 which I want to parse into a datetime object.
dtObj = datetime.strptime("Dec 03 2020 01: +0", '%b %d %Y %I: %z')
Checking the Documentation, this should work but I get the following error:
ValueError: time data 'Dec 03 2020 01: +0' does not match format '%b %d %Y %I: %z'
Any ideas what I have overseen?
Thanks in advance
Any ideas what I have overseen?
strftime.org claims that %z
UTC offset in the form ±HHMM[SS[.ffffff]] (empty string if the object
is naive).
this mean that it must contain at least 4 digits after + or - (HHMM part, which is compulsory), taking this is account Dec 03 2020 01: +0 is not compliant with used format string, whilst Dec 03 2020 01: +0000 is
import datetime
dtObj = datetime.datetime.strptime("Dec 03 2020 01: +0000", '%b %d %Y %I: %z')
print(dtObj)
gives output
2020-12-03 01:00:00+00:00
I am using time module to convert epoch into human readable date using the code below.
import time
datetime = time.strftime("%a, %d %b %Y %H:%M:%S +0000", time.localtime(1609740000000))
print(datetime)
>>> Thu, 17 Aug 52980 20:00:00 +0000
The output is incorrect when I check it on https://www.epochconverter.com
Correct output should be Wed, 04 Aug 2021 21:49:24 +0000
time.localtime takes time in seconds. You presumably pass time in milliseconds.
datetime = time.strftime("%a, %d %b %Y %H:%M:%S +0000",
time.localtime(1609740000000 // 1000))
#'Mon, 04 Jan 2021 01:00:00 +0000'
The answer from epochconverter.com is the same. Your "correct output" is incorrect.
If there was no (UTC), it would be:
%a, %d %b %Y %X %z
but server is sending with additional (UTC) or (CDT) how do you parse it?
%a, %d %b %Y %X %z (%Z) doesn't work.
How does it not work? Which version of python are you using?
I just ran the following in python 3.9:
datetime.datetime.strptime("Fri, 25 Jun 2021 12:06:16 +0000 (UTC)", "%a, %d %b %Y %X %z (%Z)")
Which created this datetime object:
datetime.datetime(2021, 6, 25, 12, 6, 16, tzinfo=datetime.timezone(datetime.timedelta(0), 'UTC'))
I've tried the following code :
import datetime
d = datetime.datetime.strptime("01/27/2012", "%m/%d/%Y")
print(d)
and the output is :
2012-01-27 00:00:00
I'am using Linux Mint :
test#testsrv ~/pythonvault $ date
Fri Jun 16 21:40:57 EEST 2017
So,the question is why the output of python code returns a date in "%Y/%m/%d" ( 2012-01-27 ) instead of "%m/%d/%Y" format ?
Please note that I'am using python 2.7
Any help would be appreciated.
You need to make sure you provide input accordingly
datetime.strptime(date_string,date_string_format).strftime(convert_to_date_string_format)
To print the date in specified format you need to provide format as below.
import datetime
d =datetime.datetime.strptime("01/27/2012","%m/%d/%Y").strftime('%m/%d/%Y')
print d
Output:
01/27/2012
>>Demo<<
datetime.strptime(date_string, format) function returns a datetime object corresponding to date_string, parsed according to format.
When you print datetime object, it is formatted as a string in ISO 8601 format, YYYY-MM-DDTHH:MM:SS
References:
https://docs.python.org/2/library/datetime.html#datetime.datetime.strptime
https://docs.python.org/2/library/datetime.html#datetime.datetime.isoformat
As astutely noted in the comments, you are parsing to a datetime object using the format you specified.
strptime(...) is String Parse Time. You have specified the format for how the string should be interpreted to initialize a Datetime object, but that format is only utilized for initialization. By default, when you go to print that datetime object, you are getting the representation of str(DatetimeObjectInstance) (in your case, str(d)).
If you want a different format, you should use String Format Time (strftime(...))
import datetime
str_time= "2018-06-03 08:00:00"
date_date = datetime.datetime.strptime(str_time, "%Y-%m-%d %H:%M:%S")
print date_date
There is a difference between datetime.strp[arse]time() and datetime.strf[ormat]time().
The first one, strptime() allows you to create a date object from a string source, provided you can tell it what format to expect:
strDate = "11-Apr-2019_09:15:42"
dateObj = datetime.strptime(strDate, "%d-%b-%Y_%H:%M%S")
print(dateObj) # shows: 2019-04-11 09:15:42
The second one, strftime() allows you to export your date object to a string in the format of your choosing:
dateObj = datetime(2019, 4, 11, 9, 19, 25)
strDate = dateObj.strftime("%m/%d/%y %H:%M:%S")
print(strDate) # shows: 04/11/19 09:19:25
What you're seeing is simply the default string format of a datetime object because you didn't explicitly tell it what format to use.
Checkout http://strftime.org/ for a list of all the different string format options that are availble.
The datetime.strptime() class method creates a datetime object from a
string representing a date and time and a corresponding format string.
%a
Weekday as locale’s abbreviated name.
Sun, Mon, …, Sat (en_US);
So, Mo, …, Sa (de_DE)
%A
Weekday as locale’s full name.
Sunday, Monday, …, Saturday (en_US);
Sonntag, Montag, …, Samstag (de_DE)
%w
Weekday as a decimal number, where 0 is Sunday and 6 is Saturday.
0, 1, …, 6
%d
Day of the month as a zero-padded decimal number.
01, 02, …, 31
%b
Month as locale’s abbreviated name.
Jan, Feb, …, Dec (en_US);
Jan, Feb, …, Dez (de_DE)
%B
Month as locale’s full name.
January, February, …, December (en_US);
Januar, Februar, …, Dezember (de_DE)
%m
Month as a zero-padded decimal number.
01, 02, …, 12
%y
Year without century as a zero-padded decimal number.
00, 01, …, 99
%Y
Year with century as a decimal number.
0001, 0002, …, 2013, 2014, …, 9998, 9999
%H
Hour (24-hour clock) as a zero-padded decimal number.
00, 01, …, 23
%I
Hour (12-hour clock) as a zero-padded decimal number.
01, 02, …, 12
%p
Locale’s equivalent of either AM or PM.
AM, PM (en_US);
am, pm (de_DE)
%M
Minute as a zero-padded decimal number.
00, 01, …, 59
%S
Second as a zero-padded decimal number.
00, 01, …, 59
%f
Microsecond as a decimal number, zero-padded to 6 digits.
000000, 000001, …, 999999
%z
UTC offset in the form ±HHMM[SS[.ffffff]] (empty string if the object is naive).
(empty), +0000, -0400, +1030, +063415, -030712.345216
%Z
Time zone name (empty string if the object is naive).
(empty), UTC, GMT
%j
Day of the year as a zero-padded decimal number.
001, 002, …, 366
%U
Week number of the year (Sunday as the first day of the week) as a zero-padded decimal number. All days in a new year preceding the
first Sunday are considered to be in week 0.
00, 01, …, 53
%W
Week number of the year (Monday as the first day of the week) as a zero-padded decimal number. All days in a new year preceding the
first Monday are considered to be in week 0.
00, 01, …, 53
%c
Locale’s appropriate date and time representation.
Tue Aug 16 21:30:00 1988 (en_US);
Di 16 Aug 21:30:00 1988 (de_DE)
%x
Locale’s appropriate date representation.
08/16/88 (None);
08/16/1988 (en_US);
16.08.1988 (de_DE)
%X
Locale’s appropriate time representation.
21:30:00 (en_US);
21:30:00 (de_DE)
%%
A literal '%' character.
%
for more information please visit official website for python
Example Programs for better understanding
Program 1:
from datetime import datetime
data = "2022-02-09 12:25:22"
dat = datetime.strptime(data, "%Y-%m-%d %H:%M:%S")
print(dat)
Output:
2022-02-09 12:25:22
Program 2:
from datetime import datetime
data = "Thursday, 10 February 2022 11:28:45 am"
dat = datetime.strptime(data, "%A, %d %B %Y %H:%M:%S %p")
print(dat)
Output:
2022-02-10 11:28:45
Given a string in the datetime format of strftime('%b %d, %Y %I:%M %p')
eg: 'Apr 17, 2016 02:00 AM'
is there a way to check if this time has already past?
like may be compare
datetime.datetime.now().strftime('%b %d, %Y %I:%M %p')
somehow to the string 'Apr 17, 2016 02:00 AM'
Parse the string into a datetime.datetime instance then compare to datetime.now():
from datetime import datetime
dt = datetime.strptime('Apr 17, 2016 02:00 AM', '%b %d, %Y %I:%M %p')
if dt < datetime.now():
print('{} alread past'.format(dt))
You might like to make that a function:
def is_past(dt_string):
return datetime.strptime(dt_string, '%b %d, %Y %I:%M %p') < datetime.now()
And then call it like this:
>>> is_past('Apr 17, 2016 02:00 AM')
False
>>> is_past('Apr 01, 2016 02:00 AM')
True
No, string comparison would not work here; the values do not sort according to the full date, but according to the month and day of the month, with the first 10 days of the month eratically dispersed throughout that sort as the day number is not zero-padded. If the year was listed first, followed by a zero-padded numeric month, day, hours (using a 24 hour clock) and minutes, then you could do it as strings only, because then the lexicographical sort happens to match the way the date and time would be sorted.
Instead, parse your string to a datetime object using the datetime.datetime.strptime() class method:
dt = datetime.datetime.strptime(string, '%b %d, %Y %I:%M %p')
if dt < datetime.datetime.now():
# in the past.
Demo:
>>> import datetime
>>> string = 'Apr 17, 2016 02:00 AM'
>>> dt = datetime.datetime.strptime(string, '%b %d, %Y %I:%M %p')
>>> dt
datetime.datetime(2016, 4, 17, 2, 0)
>>> dt < datetime.datetime.now()
False
If you were to format your dates using the ISO8601 combined date-time format, then you'd have a format that can be sorted as strings only:
>>> datetime.datetime.now().isoformat()
'2016-04-15T09:55:09.907130'