How to convert date format using python - python-3.x

I want to convert the date format from Wed Aug 16 2017 to 16/08/2017
Here is the code I tried:
datetime_object = datetime.strptime(newList[0], '%a %b %d %Y').date()
datetime_object = datetime.strptime(str(datetime_object), '%Y-%m-%d').strftime('%d/%m/%y')
print datetime_object

Try this
import datetime
dateTime = datetime.datetime.strptime("Wed Aug 16 2017", "%a %b %d %Y")
print dateTime.strftime('%d/%m/%Y')
This gives you datetime object object, out of that you can format it however you want

Related

How can I parse a custom string as a timezone aware datetime?

How can I parse
18 January 2022, 14:50 GMT-5
as a timezone aware datetime.
pytz.timezone('GMT-5')
fails.
It appears I may need to parse the GMT part, and manually apply the 5 hours offset post parsing?
Hmm How about maybe:
import re
import datetime
foo = "18 January 2022, 14:50 GMT-5"
bar = re.sub(r"[+-]\d+$", lambda m: "{:05d}".format(100 * int(m.group())), foo)
print(datetime.datetime.strptime(bar, "%d %B %Y, %H:%M %Z%z" ))
I think that gives you:
2022-01-18 14:50:00-05:00

How to convert a string into datetime with format directives from another Timezone with Python 3

I have function in my Django application that pulls informations from SSH. I get a raw date string like the following (French language):
'mar. 27 mars 2012 17:51:42 CEST'
My issue is that I need to convert this string to a datetime object before passing it to update one of my model, but I get an error.
ssh_output = 'mar. 27 mars 2012 17:51:42 CEST'
my_datetime = datetime.datetime.strptime(ssh_output,"%a. %d %B %Y %H:%M:%S CEST")
Above code throws an exception:
time data 'mar. 27 mars 2012 17:51:42 CEST' does not match format '%a.
%d %B %Y %H:%M:%S CEST'
I'm confused because locale.getlocale() outputs: "
('fr_FR', 'UTF-8')
But testing datetime format with datetime.datetime.now().strftime("%a %d %B %Y %H:%M:%S %Z") outputs (English language):
Wed 08 July 2020 15:46:11
Also, all date format directives seems correct (plus literal strings '.' and 'CEST'):
%a : Weekday as locale’s abbreviated name.
%d : Day of the month as a zero-padded decimal number.
%B : Month as locale’s full name.
%Y : Year with century as a decimal number.
%H : Hour (24-hour clock) as a zero-padded decimal number.
%M : Minute as a zero-padded decimal number.
%S : Second as a zero-padded decimal number.
So it seems that raw datetime string grabbed from SSH output 'mar. 27 mars 2012 17:51:42 CEST' can't be parsed/converted because it does not match current timezone...
How can I convert this raw datetime string into datetime in this case?
To parse CEST to the correct timezone, you could split the ssh output into the datetime part and the timezone part. After that you can apply a mapping dict:
import datetime
import dateutil
import locale
locale.setlocale(locale.LC_ALL, 'fr_FR')
ssh_output = 'mar. 27 mars 2012 17:51:42 CEST'
# assuming timezone abbreviation separated by space
parts = ssh_output.split(' ')
timestr, tzstr = ' '.join(parts[:-1]), parts[-1]
# create a custom mapping dict
tzmapping = {'CEST': dateutil.tz.gettz('Europe/Paris')}
my_datetime = datetime.datetime.strptime(timestr,"%a %d %B %Y %H:%M:%S")
my_datetime = my_datetime.replace(tzinfo=tzmapping[tzstr])
# datetime.datetime(2012, 3, 27, 17, 51, 42, tzinfo=tzfile('Europe/Paris'))

Time data with gmt does not match format input for pandas conversion

How to convert date time string with GMT into a pandas date time format ?
Here is an example :
#date_time is like 12/Dec/2015:18:25:11 +0100
df['date_time'] = pd.to_datetime(df['date_time'], format="%d/%b/%Y:%I:%M:%S %Z")
Here is the error :
ValueError: time data '12/Dec/2015:18:25:11 +0100' does not match
format '%d/%b/%Y:%I:%M:%S %Z' (match)
You'd better check the formatted string:
https://docs.python.org/3/library/datetime.html
Use '%d/%b/%Y:%H:%M:%S %z' instead of '%d/%b/%Y:%I:%M:%S %Z'.

How to format a date to a specific format in python?

I have a datetime from below generated code
from datetime import datetime
from pytz import timezone
tz = timezone('US/Pacific')
print(datetime.now(tz)) # 2019-06-17 05:41:22.189735-07:00
I am looking for this format of output
"Wed, 17 Jun 2019 05:41:22 -0700"
How can i achieve this?
You're looking for the datetime.strftime method:
print(datetime.now().strftime("%a, %d %b %Y %H:%M:%S.%f"))
i managed to fix it myself by
print(datetime.now(tz).strftime("%a, %d %B %Y %H:%M:%S %z")) # Mon, 17 June 2019 05:51:16 -0700

How to change a given date in "yyyy-MM-dd HH:mm:ss.SSS" format to "yyyy-MM-dd'T'HH:mm:ss.SSS'Z" format in groovy

How to convert a given date in yyyy-MM-dd HH:mm:ss.SSS format to yyyy-MM-dd'T'HH:mm:ss.SSS'Z' format in groovy
For example, the given date is 2019-03-18 16:20:05.6401383. I want it to converted to 2019-03-18T16:20:05.6401383Z
This is the code Used:
def date = format1.parse("2019-03-18 16:20:05.6401383");
String settledAt = format2.format(date)
log.info ">>> "+*date*+" "+*settledAt*
The result, where the date is getting changed somehow: Mon Mar 18 18:06:46 EDT 2019 & 2019-03-18T18:06:46.383Z
Thanks in advance for all the answers.
If you're on Java 8+ and Groovy 2.5+, I would use the new Date/Time API:
import java.time.*
def date = LocalDateTime.parse('2019-03-18 16:20:05.6401383', 'yyyy-MM-dd HH:mm:ss.nnnnnnn')
String settledAt = date.format(/yyyy-MM-dd'T'HH:mm:ss.nnnnnnn'Z'/)
This is presuming the input date has a "Zulu" time zone.
it's a feature of java
def date = Date.parse("yyyy-MM-dd HH:mm:ss.SSS","2019-03-18 16:20:05.6401383")
returns
Mon Mar 18 18:06:46 EET 2019
the problem that java handles only milliseconds SSS (3 digits after seconds)
but you are providing 7 digits for milliseconds 6401383
as workaround remove extra digits with regexp:
def sdate1 = "2019-03-18 16:20:05.6401383"
sdate1 = sdate1.replaceAll( /\d{3}(\d*)$/, '$1') //keep only 3 digits at the end
def date = Date.parse("yyyy-MM-dd HH:mm:ss.SSS",sdate1)
def sdate2 = date.format("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'")

Resources