Datetime strptime in python - python

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

Related

Convert seconds to date and time in python

I have a DataFrame with a column containing seconds and I would like to convert the column to date and time and save the file with a column containing the date and time .I Have a column like this in seconds
time
2384798300
1500353475
7006557825
1239779541
1237529231
I was able to do it but by only inserting the number of seconds that i want to convert with the following code:
datetime.fromtimestamp(1238479969).strftime("%A, %B %d, %Y %I:%M:%S")
output : Tuesday, March 31, 2009 06:12:49'
What i want to get is the conversion of the whole column,I tried this :
datetime.fromtimestamp(df['time']).strftime("%A, %B %d, %Y %I:%M:%S") but I can not get it, any help of how i can do it will be appreciated.
Use df.apply:
In [200]: from datetime import datetime
In [203]: df['time'] = df['time'].apply(lambda x: datetime.fromtimestamp(x).strftime("%A, %B %d, %Y %I:%M:%S"))
In [204]: df
Out[204]:
time
0 Friday, July 28, 2045 01:28:20
1 Tuesday, July 18, 2017 10:21:15
2 Wednesday, January 11, 2192 03:33:45
3 Wednesday, April 15, 2009 12:42:21
4 Friday, March 20, 2009 11:37:11

Python date time parsing

Why is this failing:
datetime.datetime.strptime(
date_string, ' %A %d %B %Y : %I:%M %p')
ValueError("time data ' Tuesday 08 September 2020 : 00:07 AM' does not match format ' %A %d %B %Y : %I:%M %p'")
when this works:
datetime.datetime.strptime(' Wednesday 02 September 2020 : 2:54 AM', ' %A %d %B %Y : %I:%M %p')
I think it must have to do with the 00 hours, but what it is exactly I do not know.
From datetime docs:
%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
So you would need input like 12:07 am for the time to be valid (there is no 0 o'clock in a 12 hour clock)
>> datetime.datetime.strptime(' Tuesday 01 September 2020 : 12:07 AM', ' %A %d %B %Y : %I:%M %p')
datetime.datetime(2020, 9, 1, 0, 7)
Or use %H for 24 hour clock, in which case you'd likely want to drop the %p since it's meaningless in this case
>> datetime.datetime.strptime(' Tuesday 01 September 2020 : 00:07', ' %A %d %B %Y : %H:%M')
datetime.datetime(2020, 9, 1, 0, 7)

pandas - converting d-mmm-yy to datetime object

I have a CSV with some data that looks like such:
I have many of these files, and I want to read them into DataFrame:
df = pd.read_csv(filepath, engine='c')
df['closingDate'] = pd.to_datetime(df['closingDate'], format='%dd-%mmm-%yy')
df['Fut Expiration Date'] = pd.to_datetime(df['Fut Expiration Date'], format='%d-%m-%yy')
I've tried a multitude of formats, but none seem to work. Is there an alternative?
Actually you do not need to specify the format here. The format is unambiguous, if we convert it without specifying a format, we get:
>>> df
Date
0 1-Dec-99
1 1-Jul-99
2 1-Jun-99
3 1-Nov-99
4 1-Oct-99
5 1-Sep-99
6 2-Aug-99
7 2-Dec-99
>>> pd.to_datetime(df['Date'])
0 1999-12-01
1 1999-07-01
2 1999-06-01
3 1999-11-01
4 1999-10-01
5 1999-09-01
6 1999-08-02
7 1999-12-02
Name: Date, dtype: datetime64[ns]
Alternatively, we can look up the format in the documentation of the datetime module [Python-doc]. We here se that:
%d Day of the month as a zero-padded 01, 02, …, 31
decimal number.
%b Month as locale’s abbreviated name. Jan, Feb, …, Dec (en_US);
Jan, Feb, …, Dez (de_DE)
%y Year without century as a 00, 01, …, 99
zero-padded decimal number.
So we can specify the format as:
>>> pd.to_datetime(df['Date'], format='%d-%b-%y')
0 1999-12-01
1 1999-07-01
2 1999-06-01
3 1999-11-01
4 1999-10-01
5 1999-09-01
6 1999-08-02
7 1999-12-02
Name: Date, dtype: datetime64[ns]
Check out the directives for datetimes here. The following should work, using 3 letter months and 2 digit years:
df['Fut Expiration Date'] = pd.to_datetime(df['Fut Expiration Date'], format='%d-%b-%y')
Use %b for a three letter month. Please see the Python strftime reference: http://strftime.org/
I think you want: w for the day, b for the month, and yy for the year.
I'm assuming the days aren't zero padded, if the days are zero padded then use d instead of w.

datetime comparison with string?

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'

How to get datetime object from string "DD Month YYY" where month is in full name ex. January

I've a string, for ex '03 July 2012' and i want a datetime object from this. I'm looking for the most optimum way to do it.
Did you read the documentation?
>>> import datetime
>>> datetime.datetime.strptime('03 July 2012', '%d %B %Y')
datetime.datetime(2012, 7, 3, 0, 0)
%d stays for day (03), %B for full month day (July) and %Y for year (2012).

Categories

Resources