Converting (YYYY-MM-DD-HH:MM:SS) date time - python

I want to convert a string like this "29-Apr-2013-15:59:02"
into something more usable.
The dashes can be easily replaced with spaces or other characters. This format would be ideal: "YYYYMMDD HH:mm:ss (20130429 15:59:02)".
Edit:
Sorry, I did not specifically see the answer in another post. But again, I'm ignorant so could have been looking at the solution and didn't know it. I've got this working, but I wouldn't consider it "pretty."
#29-Apr-2013-15:59:02
import sys, datetime, time
#inDate = sys.argv[1]
inDate = 29-Apr-2013-15:59:02
def getMonth(month):
monthDict = {'Jan':'01','Feb':'02','Mar':'03','Apr':'04','May':'05','Jun':'06','Jul':'07','Aug':'08','Sep':'09','Oct':'10','Nov':'11','Dec':'12'}
for k, v in monthDict.iteritems():
if month == k:
return v
day = inDate[:2]
#print day
month = inDate[3:6]
#print month
year = inDate[7:11]
#print year
time = inDate[-8:]
#print time
newDate = year+getMonth(month)+day
newDateTime = newDate+" "+time
print newDate
print newDateTime
Any thoughts on improving?

Use datetime.strptime() to parse the inDate string into a date object, use datetime.strftime() to output in whatever format you like:
>>> from datetime import datetime
>>> inDate = "29-Apr-2013-15:59:02"
>>> d = datetime.strptime(inDate, "%d-%b-%Y-%H:%M:%S")
>>> d
datetime.datetime(2013, 4, 29, 15, 59, 2)
>>> d.strftime("YYYYMMDD HH:mm:ss (%Y%m%d %H:%M:%S)")
'YYYYMMDD HH:mm:ss (20130429 15:59:02)'

Have you investigated dateutil?
http://labix.org/python-dateutil
I found a similar question to yours:
How do I translate a ISO 8601 datetime string into a Python datetime object?

You want to look into datetime, in particular strptime.

Related

Reversing the date order of "%Y-%m-%d" to "%d-%m-%Y"

Using todays date, I would like to reformat the date so that it reads as follows:
25-09-2021
So far I have come up with a very clumsy way of doing:
from datetime import datetime, timedelta, date
print(datetime.now())
the_date = datetime.strftime(datetime.now(), '%Y-%m-%d')
print(the_date)
a = the_date[-2:]
print(a)
b = the_date[5:-3]
print(b)
c = the_date[:4]
print(c)
new_date = str(a)+'-'+str(b)+'-'+str(c)
print(new_date)
Surely there is a cleaner way of doing this?
You could simply specify the formula differently:
datetime.strftime(datetime.now(), '%d-%m-%Y')
It is not clear what type of data you are starting with. If you have an existing date string in the format YYYY-MM-DD, you can split and reorder it.
Here's an example.
date = '2021-09-25'
Y, M, D = date.split('-')
date = f"{D}-{M}-{Y}"
print(date) # Prints 25-09-2021
Assuming you start with a string with the given format
original_date_str = datetime.now().strftime('%Y-%m-%d')
#this line recreates a datetime object from the string
original_date_datetime = datetime.strptime(original_date_str, '%Y-%m-%d')
#this value will be a string with the new format
new_fmt_date_str = original_date_datetime.strftime("%d-%m-%Y")
I haven't tested the code yet, but pending some silly mistake it should work.

Python: convert date format YYYY-mm-dd to dd-MON-yyyy with abbreviated month

I have a date that is a string in this format:
'2021-01-16'
And need to convert it to a string in this format:
'16-JAN-2021'
I am able to get most of it like this:
x = datetime.strptime('2021-01-16', '%Y-%m-%d')
x.strftime('%d-%b-%Y')
But the month is not fully capitalized:
'16-Jan-2021'
Just use upper() to capitalize the output string:
from datetime import datetime
x = datetime.strptime('2021-01-16', '%Y-%m-%d')
print(x.strftime('%d-%b-%Y').upper())
# 16-JAN-2021
You were almost there. Simply use upper().
>>> from datetime import datetime
>>> datetime.strptime('2021-01-16', '%Y-%m-%d').strftime('%d-%b-%Y').upper()
'16-JAN-2021'
x.strftime('%d-%b-%Y').upper()
I read answers with upper() function, here is another way using %^b
from datetime import datetime
date = datetime.strptime('2011-01-16', '%Y-%m-%d')
formatted_date = date.strftime('%d-%^b-%Y')
print(formatted_date)
Goodluck!

python json date object to python datetime

I have a JSON object with a date that returns
print row['ApplicationReceivedDateTime']
/Date(1454475600000)/
how do I process this using the pythons datetime module?
print type(row['ApplicationReceivedDateTime'])
returns <type 'unicode'>
print repr(row['ApplicationReceivedDateTime'])
returns u'/Date(1454475600000)/'
That looks like milliseconds. Try dividing by 1000.
import datetime as dt
>>> dt.datetime.fromtimestamp(1454475600000 / 1000)
datetime.datetime(2016, 2, 2, 21, 0)
If the date is in the string format per your question, extract the numeric portion using re.
date = '/Date(1454475600000)/'
>>> dt.datetime.fromtimestamp(int(re.findall(r"\d+", date)[0]) / 1000)
datetime.datetime(2016, 2, 2, 21, 0)
You probably want
datetime.datetime.strptime(string_date, "%Y-%m-%d %H:%M:%S.%f")
And the values of Year, Month, Day, Hour, Minute, Second and F, for that you can write a manual function for that like this
def generate_date_time_str(date_str):
"""Login to parse the date str"""
return date_str
the date_str will look link this
"%Y-%m-%d %H:%M:%S.%f"
There is no python module directly convert any random date str to DateTime object
You can use re to get the integer value and then use datetime.datetime.fromtimestamp to get the date value:
from datetime import datetime
import re
string_time = row['ApplicationReceivedDateTime']
parsed_time = int(re.search('\((\d+)\)', string_time)[1]) / 1e3 #1e3 == 1000
rcvd_date = datetime.fromtimestamp(parsed_time)
print(rcvd_date.strftime('%Y-%m-%d %H:%M:%S'))
Prints:
'2016-02-03 05:00:00'

Date Time Formats in Python

What are these date-time formats? I need to convert them to the same format, to check if they are the same. These are just two coming from a separate data source, so I need to find a way to make them the same format. Any ideas?
2013-07-12T07:00:00Z
2013-07-10T11:00:00.000Z
Thanks in advance
That extra .000 is micro seconds.
This will convert a date string of a format to datetime object.
import datetime
d1 = datetime.datetime.strptime("2013-07-12T07:00:00Z","%Y-%m-%dT%H:%M:%SZ")
d2 = datetime.datetime.strptime("2013-07-10T11:00:00.000Z","%Y-%m-%dT%H:%M:%S.%fZ")
Then convert them into any format depending on your requirement, by using:
new_format = "%Y-%m-%d"
d1.strftime(new_format)
perhaps use .isoformat()
string in ISO 8601 format, YYYY-MM-DDTHH:MM:SS[.mmmmmm][+HH:MM]
>>> import datetime
>>> datetime.datetime.utcnow().isoformat() + "Z"
'2013-07-11T22:26:51.564000Z'
>>>
Z specifies "zulu" time or UTC.
You can also add the timezone component by making your datetime object timezone aware by applying the appropriate tzinfo object. With the tzinfo applied the .isoformat() method will include the appropriate utc offset in the output:
>>> d = datetime.datetime.utcnow().replace(tzinfo=datetime.timezone.utc)
>>> d.isoformat()
'2019-11-11T00:52:43.349356+00:00'
You can remove the microseconds by change the microseconds value to 0:
>>> no_ms = d.replace(microsecond=0)
>>> no_ms.isoformat()
'2019-11-11T00:52:43+00:00'
Also, as of python 3.7 the .fromisoformat() method is available to load an iso formatted datetime string into a python datetime object:
>>> datetime.datetime.fromisoformat('2019-11-11T00:52:43+00:00')
datetime.datetime(2019, 11, 11, 0, 52, 43, tzinfo=datetime.timezone.utc)
http://www.ietf.org/rfc/rfc3339.txt
you can try to trim the string
data = "2019-10-22T00:00:00.000-05:00"
result1 = datetime.datetime.strptime(data[0:19],"%Y-%m-%dT%H:%M:%S")
result2 = datetime.datetime.strptime(data[0:23],"%Y-%m-%dT%H:%M:%S.%f")
result3 = datetime.datetime.strptime(data[0:9], "%Y-%m-%d")
use datetime module.
For a variable
import datetime
def convertDate(d):
new_date = datetime.datetime.strptime(d,"%Y-%m-%dT%H:%M:%S.%fZ")
return new_date.date()
convertDate("2019-12-23T00:00:00.000Z")
you can change the ".date()" to ".year", ".month", ".day" etc...
Output: # is now a datetime object
datetime.date(2019, 12, 23)
For a DataFrame column, use apply()
df['new_column'] = df['date_column'].apply(convertDate)
* Short and best way:
str(datetime.datetime.now()).replace(' ','T')
or
str(datetime.datetime.now()).replace(' ','T') + "Z"

Given a date in a specific format, how can I determine age in months?

I have a script that gets a string in the form of 3/4/2013. How can I convert that to a date that I can then use to determine the age of the date (in months)? I would also like to be able to have the month in decimal form (i.e. 2.8 months old).
I'm not sure what to do at all as far as coding this. I've read about different libraries that can do things like this, but I'm not sure what one is best.
EDIT: Assume a month has 30 days. This is what I have so far:
import time
def ageinmonths( str )
return time.today() - time.strptime("3/4/2013", "%b %d %y")
This is the answer from kzh but with the addition of the decimal that the poster wanted.
from datetime import datetime
from dateutil.relativedelta import relativedelta
date = '3/4/2013'
dt = datetime.strptime(date,'%m/%d/%Y')
r = relativedelta(datetime.now(), dt)
months = r.years * 12 + r.months + r.days/30.
print months
>>>> 3.33333333333
EDIT: for ultimate transatlantic date-formatting harmony!
import datetime,locale
def transatlantic_age_in_months(datestring):
datefmt = locale.nl_langinfo(locale.D_FMT)
dob = datetime.datetime.strptime(datestring,datefmt[:-2]+'%Y')
dt = dob.today() - dob
return dt.days/30.
Something like this:
>>> from datetime import datetime
>>> from dateutil.relativedelta import relativedelta
>>> dt = datetime.strptime('3/4/2013','%m/%d/%Y')
>>> r = relativedelta(datetime.now(), dt)
>>> months = r.years * 12 + r.months + r.days/30
I would use str.split('/') and then manipulate each index of the list that way.This way means you can work with the day/month/year individually to calculate the necessary values.
High-level approach:
Convert your date to a datetime object. Call datetime.now(). Subtract. Noodle result into months.

Categories

Resources