Converting 23/Oct/2014 to 2014/10/23 in Python - python

I have date strings in the form of '23/Oct/2014' and want to convert it to '2014/10/23' in Python 3. The final output I need is just as a string. I implementing my own function to do the conversion using dictionary (for month conversion) but I am wondering if there is more pythonic way of doing the same thing.

You can use the datetime library to parse the string, then format back to a string again:
from datetime import datetime
converted = datetime.strptime(original, '%d/%b/%Y').strftime('%Y/%m/%d')
This parses the input string using datetime.datetime.strptime(), then formats the resulting object to a string again with datetime.datetime.strftime().
Demo:
>>> from datetime import datetime
>>> original = '23/Oct/2014'
>>> datetime.strptime(original, '%d/%b/%Y').strftime('%Y/%m/%d')
'2014/10/23'

If you just want a string, your dict mapping and format would work fine, if you don't want datetime objects I don't see the point in using datetime:
dt = '23/Oct/2014'
dates = dict(Jan="01", Feb="02", Mar="03", Apr="04", May="05", Jun="06", Jul="07", Aug="08", Sep="09", Oct="10",
Nov="11", Dec="12")
day,mon, year = dt.split("/")
print("{}/{}/{}".format(year,dates[mon],day))
2014/10/23

Related

Convert custom string date to date

Is there a way to convert a string date that is stored in some non-traditional custom manner into a date using datetime (or something equivalent)? The dates I am dealing with are S3 partitions that look like this:
year=2023/month=2/dayofmonth=3
I can accomplish this with several replaces but im hoping to find a clean single operation to do this.
You might provide datetime.datetime.strptime with format string holding text, in this case
import datetime
dt = datetime.datetime.strptime("year=2023/month=2/dayofmonth=3","year=%Y/month=%m/dayofmonth=%d")
d = dt.date()
print(d) # 2023-02-03
you can do that converting your string into a date object using "datetime" combined with strptime() method.
The strtime() takes two arguments, the first is the string to be parsed, and the second a string with the format.
Here's an example:
from datetime import datetime
# your string
date_string = "year=2023/month=2/dayofmonth=3"
# parse the string into a datetime object
date = datetime.strptime(date_string, "year=%Y/month=%m/dayofmonth=%d")
# print the datetime object
print(date)

Unable to return only time from datetime object

I have some columns which has time in string format like '01:19:55' and so on. I want to convert this string into time format. For that, I am trying to use the code like below:
col_list2=['clm_rcvd_tm','gtwy_rcvd_tm']
pandas_df_1=df2.toPandas()
for x in col_list2:
pandas_df_1[x]=pd.to_datetime(pandas_df_1[x].replace(" ",""),format='%H:%M:%S').dt.time
As an output, these clumns are returning decimal values. (Ex:0.26974537037037)
Any help will be appreciated.
If you have a string in your pandas dataframe as you mentioned i.e;
01:19:55 so that you can easily convert this by using python datetime module
For example;
import datetime
str = "01:19:55"
dt = datetime.strptime(str, '%H:%M:%S') # for 24 hour format
dt = datetime.strptime(str, '%I:%M:%S') # for 12 hour format
for references have a look
Python Datetime formating

how to convert datetime to numeric format in Python

I have following datetime in Python and want to convert it to numeric
2020-04-01 12:30:01
When I convert this to number in excel it returns 43922.5208449074. How to get the same number in Python?
I tried with following
datetime.fromisoformat('2020-04-01 12:30:01').timestamp()
But it does not return me the same number. How can we do it in Python
If i am understanding your problem,
you can use it
# Importing datetime.
from datetime import datetime
# Creating a datetime object so we can test.
a = datetime.now()
# Converting a to string in the desired format (YYYYMMDD) using strftime
# and then to int.
a = int(a.strftime('%Y%m%d'))
print (a)

Convert year from unicode format to python's datetime format

I have only year parameter as input in the following manner:
2014,2015,2016
I want to convert each element from my list into python's datetime format. Is it possible to do this kind of things if the only given parameter is the year ?
Just set month and day manually to 1
from datetime import date
YearLst = [2014,2015,2016]
map(lambda t: date(t, 1, 1),YearLst)

strip date with -07:00 timezone format python

I have a variable 'd' that contains dates in this format:
2015-08-03T09:00:00-07:00
2015-08-03T10:00:00-07:00
2015-08-03T11:00:00-07:00
2015-08-03T12:00:00-07:00
2015-08-03T13:00:00-07:00
2015-08-03T14:00:00-07:00
etc.
I need to strip these dates, but I'm having trouble because of the timezone. If I use d = dt.datetime.strptime(d[:19],'%Y-%m-%dT%H:%M:%S'), only the first 19 characters will appear and the rest of the dates are ignored. If I try d = dt.datetime.strptime(d[:-6],'%Y-%m-%dT%H:%M:%S, Python doesn't chop off the timezone and I still get the error ValueError: unconverted data remains: -07:00. I don't think I can use the dateutil parser because I've only seen it be used for one date instead of a whole list like I have. What can I do? Thanks!
Since you have a list just iterate over and use dateutil.parser:
d = ["2015-08-03T09:00:00-07:00","2015-08-03T10:00:00-07:00","2015-08-03T11:00:00-07:00","2015-08-03T12:00:00-07:00",
"2015-08-03T13:00:00-07:00","2015-08-03T14:00:00-07:00"]
from dateutil import parser
for dte in d:
print(parser.parse(dte))
If for some reason you actually want to ignore the timezone you can use rsplit with datetime.strptime:
from datetime import datetime
for dte in d:
print(datetime.strptime(dte.rsplit("-",1)[0],"%Y-%m-%dT%H:%M:%S"))
If you had a single string delimited by commas then just use d.split(",")
You can use strftime to format the string in any format you want if you actually want a string:
for dte in d:
print(datetime.strptime(dte.rsplit("-",1)[0],"%Y-%m-%dT%H:%M:%S").strftime("%Y-%m-%d %H:%M:%S"))

Categories