Change Date Format In Python [duplicate] - python

This question already has answers here:
Convert string "Jun 1 2005 1:33PM" into datetime
(26 answers)
Closed 8 years ago.
I need to convert date string "Dec 17 00:00:06" to string "2014-12-17 00:00:06" in python. I looked at the datetime.strptime but still can't find a way for this.
eg:
Dec 17 00:00:06 to 2014-12-17 00:00:06

You can use datetime module.
For e.g.
>>> import datetime
>>> do = datetime.datetime.strptime("Dec 17 2014 00:00:06", "%b %d %Y %H:%M:%S")
>>> do.strftime("%Y-%m-%d %H:%M:%S")
'2014-12-17 00:00:06'
We can replace year value to 2014 like following:
>>> do = datetime.datetime.strptime("Dec 17 00:00:06", "%b %d %H:%M:%S")
>>> do.strftime("%Y-%m-%d %H:%M:%S")
'1900-12-17 00:00:06'
>>> do1 = do.replace(year=2014)
>>> do1.strftime("%Y-%m-%d %H:%M:%S")
'2014-12-17 00:00:06'
If we want only time value then we can try like-
>>> do = datetime.datetime.strptime("Dec 17 00:00:06", "%b %d %H:%M:%S")
>>> do.strftime("%H:%M:%S")
'00:00:06'
Updated: update datetime string from file with its time string.
Algo:
Get content from the input text file.
Used re module i.e regular expression to get all pattern from content.
Use set method to remove duplicate values.
Convert datetime string to time string and update content.
Write new content into same file or other file.
code is:-
import datetime
import re
p = "/home/vivek/Desktop/input.txt"
with open(p, "rb") as fp:
content = fp.read()
date_values = set(re.findall("\[([^]]+)\]", content))
for i in date_values:
do = datetime.datetime.strptime(i, "%b %d %H:%M:%S")
content = content.replace("[%s]"%i, "%s"%(do.strftime("%H:%M:%S")) )
p = "/home/vivek/Desktop/output.txt"
with open(p, "wb") as fp:
fp.write(content)

Using datetime module will help you out.
from datetime import datetime
Firstly convert your date string to a datetime object by writing the line below.
date_obj = datetime.strptime("Dec 17 2014 00:00:06", "%b %d %Y %H:%M:%S")
Then convert that date object to a string.
date_obj.strftime("%Y-%m-%d %H:%M:%S")
You can change the parameters of the above strftime() function, and get different formats as per your requirments. Please follow python datetime
Here is the link to the options for the parameters which can be passed in the strftime() function parameter options
Go and play around as per your requirement.

from dateutil import parser
parser.parse('Dec 17 00:00:06').isoformat()
>>> '2015-12-17T00:00:06'

Related

Split URL at - With Python

Does anyone know how I can extract the end 6 characters in a absoloute URL e.g
/es/ideas-de-trading-y-noticias/el-ibex-35-insiste-en-buscar-los-7900-puntos-a-la-espera-de-las--221104
This is not a typical URL sometimetimes it ends -221104
Also, is there a way to turn 221104 into the date 04 11 2022 easily?
Thanks in advance
Mark
You should use the datetime module for parsing strings into datetimes, like so.
from datetime import datetime
url = 'https://www.ig.com/es/ideas-de-trading-y-noticias/el-ibex-35-insiste-en-buscar-los-7900-puntos-a-la-espera-de-las--221104'
datetime_string = url.split('--')[1]
date = datetime.strptime(datetime_string, '%y%m%d')
print(f"{date.day} {date.month} {date.year}")
the %y%m%d text tells the strptime method that the string of '221104' is formatted in the way that the first two letters are the year, the next two are the month, and the final two are the day.
Here is a link to the documentation on using this method:
https://docs.python.org/3/library/datetime.html#strftime-and-strptime-behavior
If the url always has this structure (that is it has the date at the end after a -- and only has -- once), you can get the date with:
str_date = str(url).split("--")[1]
Relaxing the assumption to have only one --, we can have the code working by just taking the last element of the splitted list (again assuming the date is always at the end):
str_date = str(url).split("--")[-1]
(Thanks to #The Myth for pointing that out)
To convert the obtained date into a datetime.date object and get it in the format you want:
from datetime import datetime
datetime_date = datetime.strptime(str_date, "%y%m%d")
formatted_date = datetime_date.strftime("%d %m %Y")
print(formatted_date) # 04 11 2022
Docs:
strftime
strptime
behaviour of the above two functions and format codes
Taking into consideration the date is constant in the format yy-mm-dd. You can split the URL by:
url = "https://www.ig.com/es/ideas-de-trading-y-noticias/el-ibex-35-insiste-en-buscar-los-7900-puntos-a-la-espera-de-las--221104"
time = url[-6:] # Gets last 6 values
To convert yy-mm-dd into dd mm yy we will use the DateTime module:
import datetime as dt
new_time = dt.datetime.strptime(time, '%y%m%d') # Converts your date into datetime using the format
format_time = dt.datetime.strftime(new_time, '%d-%m-%Y') # Format
print(format_time)
The whole code looks like this:
url = "https://www.ig.com/es/ideas-de-trading-y-noticias/el-ibex-35-insiste-en-buscar-los-7900-puntos-a-la-espera-de-las--221104"
time = url[-6:] # Gets last 6 values
import datetime as dt
new_time = dt.datetime.strptime(time, '%y%m%d') # Converts your date into datetime using the format
format_time = dt.datetime.strftime(new_time, '%d %m %Y') # Format
print(format_time)
Learn more about datetime
You can use python built-in split function.
date = url.split("--")[1]
It gives us 221104
then you can modify the string by rearranging it
date_string = f"{date[4:6]} {date[2:4]} {date[0:2]}"
this gives us 04 11 22
Assuming that -- will only be there as it is in the url you posted, you can do something as follows:
You can split the URL at -- & extract the element
a = 'https://www.ig.com/es/ideas-de-trading-y-noticias/el-ibex-35-insiste-en-buscar-los-7900-puntos-a-la-espera-de-las--221104'
desired_value = a.split('--')[1]
& to convert:
from datetime import datetime
converted_date = datetime.strptime(desired_value , "%y%m%d")
formatted_date = datetime.strftime(converted_date, "%d %m %Y")

How to convert string in to date in Python [duplicate]

This question already has answers here:
Python date string to date object
(9 answers)
Closed 1 year ago.
I have a string:
dat="012915"
I want to convert it to a date:
01-29-2015
I tried:
import datetime
from datetime import datetime
dat="012915"
dat = datetime.strptime(dat, '%m%d%Y').date()
dat
but failed:
ValueError: time data '01-29-15' does not match format '%m%d%Y'
%Y is for full year
%y is the short version for year
Your code is totally fine, just change the year directive to lowercase %y will do.
import datetime
from datetime import datetime
dat="012915"
dat = datetime.strptime(dat, '%m%d%y').date()
dat
I think you are looking for
import datetime
from datetime import datetime
dat="012915"
#lower %y
dat = datetime.strptime(dat, '%m%d%y').date()
print(dat)
this will give you
2015-01-29
Trying this out; changing the format string to '%m%d%y' seems to work. Looking at the python docs:
%y Year without century as a zero-padded decimal number.
%Y Year with century as a decimal number.
So the first one is what you need. Source: https://docs.python.org/3/library/datetime.html#strftime-and-strptime-format-codes
import datetime
from datetime import datetime
dat="012915"
dat = datetime.strptime(dat, '%m%d%y').date()
print(dat)
Change %Y to %y. If you want to use %Y, change dat to '01292015'.
y% is formatted as 15 while %Y is formatted as 2015.
from datetime import datetime
date_str = '012915'
date_obj = datetime.strptime(date_str, '%m/%d/%y')
print("The type of the date is now", type(date_obj))
print("The date is", date_obj)

Extract 'WeekDay Month Date HH:MM:SS' from Filename?

I have files which contain the full date and time in its name. I want to extract the particular format and print that as my first line of CSV I am writing.
My file name is like below:
VIN5_2019-04-03_10-21-26_38
I want the first line of my CSV to print as below:
date Wed Apr 3 10:21:26.000 am 2019
My code is below:
import can
import csv
import datetime
import re
filename = open('C:\\Users\\xyz\\files\\time_linear_Hexa.csv', "w")
log1 = can.BLFReader('C:\\Users\\xyz\\blf files\\VIN5_2019-04-03_10-33-59_39.blf')
filename.write(re.search("([0-9]{4}\-[0-9]{2}\-[0-9]{2})", filename))
filename.write('base hex timestamps absolute\ninternal events logged \n// version 11.0.0 \n')
How can I achieve date and time in the same format as the file image like shown in the screenshot below?
Using regex and datetime module.
Ex:
import re
import datetime
s = "VIN5_2019-04-03_10-21-26_38"
m = re.search(r"[A-Z]+\d_(?P<date>\d{4}\-\d{2}\-\d{2})_(?P<time>\d{2}\-\d{2}\-\d{2})", s)
if m:
print(datetime.datetime.strptime("{} {}".format(m.group('date'), m.group('time')), "%Y-%m-%d %H-%M-%S").strftime("%a %b %d %H:%M:%S.%f %p %Y"))
Output:
Wed Apr 03 10:21:26.000000 AM 2019
You can use a lookahead and loosbehind to extract the datetime string, use strptime to convert it to a datetime object and then use strftime to formate it to the desired form.
import re
import datetime from datetime
s = "VIN5_2019-04-03_10-21-26_38"
res = re.search('(?<=\w{5})[\w-]*(?=_\d{2})', s)
dt_string = res[0]
dt = datetime.strptime(dt_string, '%Y-%m-%d_%H-%M-%S')
'{} {} {}'.format(dt.strftime('%a %b %d %H:%M:%S.%f')[:-3], dt.strftime('%p').lower(), dt.strftime('%Y'))

Date time format conversion in python [duplicate]

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))

Convert string datetime to timestamp and vice verse in python [duplicate]

This question already has answers here:
Convert string "Jun 1 2005 1:33PM" into datetime
(26 answers)
Closed 8 years ago.
I have a date stored as a string:-
16/07/2014 13:00:00
I want to convert this into timestamp.
Also from timestamp to this format again.
Please suggest the best possible way to do this in python.
You can use datetime to handle combined dates and times. You could parse this string using datetime.strptime but then you'd have to manually select the formatting.
Alternatively you can use the dateutil package which has a parser which can intelligently guess the string format and return a datetime object, as shown below:
from dateutil import parser
s = '16/07/2014 13:00:00'
d = parser.parse(s)
print(d)
# 2014-07-16 13:00:00
print(type(d))
# datetime.datetime
The documentation to look into this deeper is here
The functions you are looking for are time.strptime(string[, format]) to go from string to timestamp, and then from timestamp to string is time.strftime(format[, t])
Here is an example for your format:
>>> from datetime import datetime
>>>
>>> date_object = datetime.strptime('16/07/2014 13:00:00', '%d/%m/%Y %H:%M:%S')
>>> print date_object
2014-07-16 13:00:00
The to go back to your format (I have used gmtime() to get the current time to show you can convert any datetime to your desired format)
>>> from time import gmtime, strftime
>>> date_string = strftime("%d/%m/%Y %H:%M:%S", gmtime())
>>> print date_string
17/09/2014 09:31:00
Your best bet is the datetime library: https://docs.python.org/2/library/datetime.html
import datetime
mytime='16/07/2014 13:00:00'
pythontime=datetime.datetime.strptime(mytime, '%d/%m/%Y %H:%M:%S')
stringtime=pythontime.strftime('%d/%m/%Y %H:%M:%S')
Enjoy!

Categories

Resources