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
Related
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
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'))
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'.
I am trying to write a variable and the date and time on the same line to a file, which will simulate a log file.
Example: July 25 2018 6:00 pm - Variable contents here
So far I am able to write the variable to the file but I am unsure how to use the datetime library or other similar libraries. Some guidance would be appreciated.
Below is the current script.
import subprocess
import datetime
var = "test"
with open('auditlog.txt', 'a') as logfile:
logfile.write(var + "\n")
The fastest way I found is doing something like this:
import time
var = time.asctime()
print(var)
Result: Thu Jul 26 00:46:04 2018
If you want to change the placements of y/m/d etc. you can alternatively use this:
import time
var = time.strftime("%B %d %Y %H:%M pm", time.localtime())
print(var)
Result: July 26 2018 00:50 pm
Have a look here.
By the way, is the subprocess intended in your code? You don't need it to open/write to files. Also you should do logfile.close() in your code after you wrote to it.
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