How to create date timestamp logs like git log - python

Using datetime.datetime.now(), I receive some badly formatted timestamps.
Is there an intuitive way of creating a date timestamp in this format?
Wed Aug 7 13:38:59 2019 -0500
This is seen in git log.

You can use datetime.datetime.strftime() to format dates as shown below:
from datetime import datetime
d = '2019-08-07 13:38:59-0500'
d2 = datetime.strptime(d, '%Y-%m-%d %H:%M:%S%z')
d3 = d2.strftime('%a %b %d %H:%M:%S %Y %z')
print(d3)
This returns:
Wed Aug 07 13:38:59 2019 -050000
This website is a great resource for strftime formatting.

You can still use the datetime library. Using strftime, you can rewrite the datetime object into a nicely formatted string.
In your case, you are going for Wed Aug 7 13:38:59 2019 -0500, which translated to strftime formatting is "%a %b %d %H:%M:%S %Y %z".
Overall, it'd be
datetime.datetime.now().strftime("%a %b %d %H:%M:%S %Y %z")
Which will give a string that looks like 'Wed Aug 7 13:38:59 2019 -0500'.

I would do the following:
from time import gmtime, strftime
if __name__ == "__main__":
time = strftime("%a, %d %b %Y %H:%M:%S +0000", gmtime())
print(time)
This was found on the documentation page of the time module. There are also a lot of additional features you might be interested in using outlined here: https://docs.python.org/3/library/time.html#time.strftime

Related

How can I convert datetime to unix timestamp in python

I have one date format "Mon, 15 Jun 2020 22:11:06 PT" I want to convert this format to unix timestamp.
I am using the following code ===>
news_date = datetime.strptime(news_date, '%a, %d %b %Y %H:%M:%S %Z')
news_date = calendar.timegm(news_date.utctimetuple())
But gives the following error ===>
ValueError: time data 'Mon, 15 Jun 2020 22:11:06 PT' does not match format '%a, %d %b %Y %H:%M:%S %Z'
How can i solve it and get the unix timestamp from this?
%Z can't parse the timezone name PT - I suggest you skip parsing it and add it "manually" instead:
from datetime import datetime
import dateutil
news_date = "Mon, 15 Jun 2020 22:11:06 PT"
# parse string without the timezone:
news_date = datetime.strptime(news_date[:-3], '%a, %d %b %Y %H:%M:%S')
# add the timezone:
news_date = news_date.replace(tzinfo=dateutil.tz.gettz('US/Pacific'))
# extract POSIX (seconds since epoch):
news_date_posix = news_date.timestamp()
# 1592284266.0
if you have multiple strings with different timezones, you could use a dict to map the abbreviations to time zone names, e.g.
tzmapping = {'PT': 'US/Pacific'}
news_date = "Mon, 15 Jun 2020 22:11:06 PT"
# get appropriate timezone from string, according to tzmapping:
tz = dateutil.tz.gettz(tzmapping[news_date.split(' ')[-1]])
# parse string and add timezone:
news_date_datetime = datetime.strptime(news_date[:-3], '%a, %d %b %Y %H:%M:%S')
news_date_datetime = news_date_datetime.replace(tzinfo=tz)

How to strip date time in python

From a website I'm getting a date in such format: Sun Jan 22 21:32:58 +0000 2012. I understand that I must get rid of +0000 to convert it to the date, but how exactly I can do it? I read the documentation but my code is not working:
from datetime import datetime
strDate = 'Mon Apr 29 14:30:53 2019'
objDate = datetime.strptime(strDate, '%a %b %H %M %S %Y')
I'm getting an error:
ValueError: time data 'Mon Apr 29 14:30:53 2019' does not match format '%d %m %H %M %S %Y'
And I don't really understand why. Or anyone knows how I can get a date from Sun Jan 22 21:32:58 +0000 2012?
If your object is datetime.datetime you can just simply do date()
from datetime import datetime
datetime1 = datetime.now()
date1 = datetime1.date()
One line solution:
strDate ='Sun Jan 22 21:32:58 +0000 2012'
objDate = datetime.strptime(strDate, '%a %b %d %H:%M:%S +%f %Y')
print(objDate)
#2019-04-29 14:30:53
Details:
You just forgot to use %d in order to capture the date number and the : for the time and you ALSO need to capture +0000.
Proof:
I'm afraid that the currently accepted answer, by seralouk, is incorrect. Using "+%f" turns the numbers into fractions of seconds. It's fine for 0000, but will mess things up if they happen to be anything else.
This is because the "+0000" part is a time zone offset, and the proper way to parse it is by using the "%z" directive, which will handle the "+" sign as well, so remove that from the format string:
>>> date_string = "Sun Jan 22 21:32:58 +0000 2012"
>>> datetime.strptime(date_string, "%a %b %d %H:%M:%S %z %Y")
datetime.datetime(2012, 1, 22, 21, 32, 58, tzinfo=datetime.timezone.utc)
You're missing colons : and the day format string %d. See the official documentation of strptime for a table that shows the different formatting values.
from datetime import datetime
strDate = 'Mon Apr 29 14:30:53 2019'
objDate = datetime.strptime(strDate, '%a %b %d %H:%M:%S %Y')
You can get rid of the '+0000' like this:
from datetime import datetime
strDate ='Sun Jan 22 21:32:58 +0000 2012'
objDate = datetime.strptime(strDate.replace(strDate.split(" ")[4] + " ", ""), '%a %b %d %H:%M:%S %Y')
print(objDate)
-> 2012-01-22 21:32:58
By the way,
1. The example of code that you post is not the one for the problem that you are asking about! (it does not include the +0000 in the string).
2. The error that you share (false format of the date, which has been answered already and described f.ex. here) is for another code, not the one you present above! (Error throws '%d %m %H %M %S %Y' instead of '%a %b %H %M %S %Y').
In your string u are missing the %d to catch the Day of month 01-31
'%a %b %d %H:%M:%S %Y'
If u want also to catch the +0000 u have to use the %z notation
Use this as a refrence to build your string correctly:
http://strftime.org/

Python Given a date, time, hour... how can i get it's formated ISO ZULU

I have been using python IMAP protocol and I read email headers and retrieve the Date which looks like
myDate --> Fri, 22 Feb 2019 17:00:06 +0000
I need to find the equivalent UTC ISO8601 with zulu formatting how can I do that?
I tried:
dateInUTCIso= datetime.datetime.strptime(myDate, '%a, %d %b %Y %H:%M:%S +%f').date().isoformat()
but I am only getting year/month/date
dateInUTCIso= 2019-02-22
Remove the .date() method call
myDate = "Fri, 22 Feb 2019 17:00:06 +0000"
dateInUTCIso= datetime.datetime.strptime(myDate, '%a, %d %b %Y %H:%M:%S +%f').isoformat() + 'Z'
# 2019-02-22T17:00:06Z
You're calling .date().isoformat(). Without .date() you would get the ISO format.
However, if you want Z instead of +00:00 at the end, you'll have to swap out that part after the fact with .replace('+00:00', 'Z') on the string output

Convert string to DateTime for mysql in python

I want to convert my date into DateTime object for MySQL.
My string format is: Mon Aug 27 04:47:45 +0000 2018
Expected Output: 'YYYY-M-D H:mm:ss'
from datetime import datetime
t = datetime.strptime('Mon Aug 27 04:47:45 +0000 2008', '%a %b %d %H:%M:%S % z %Y')
t.strftime('%Y-%m-%d %H:%M:%S')
Refer section 8.1.8
here
If you are using python 3, this solution would work -
from datetime import datetime
x = 'Mon Aug 27 04:47:45 +0000 2018'
x = datetime.strftime(datetime.strptime(x, '%a %b %d %I:%M:%S %z %Y'), '%Y-%m-%d %H:%M:%S')
# OP '2018-08-27 04:47:45'
But for python 2, you might get a ValueError: 'z' is a bad directive.... In that case, you'll either have to use something like pytz or dateutil. The table that you need to look for all these conversions can be found here
Edit: You can't have Expected Output: 'YYYY-M-D H:mm:ss' if you convert your datetime string to datetime object. Datetime object has it's own format. Above gives you a string of the format that you want
from datetime import datetime
date_as_dt_object = datetime.strptime(dt, '%a %b %d %H:%M:%S %z %Y')
You can use date_as_dt_object in a raw query or an ORM. If used in a raw query pass it as a string like:
query = "select * from table where date >" + str(date_as_dt_object)
Check out this list for Python's strftime directives.
http://strftime.org/

How can I use DateTime to get the time to this format?

'Wed, 18 Sep 2013 22:22:44 -0700'
I tried datetime.datetime.now().strftime, but I can't get it perfectly in that format.
Looks like you want:
datetime.datetime.now().strftime('%a, %d %b %Y %H:%M:%S %z')
More info here
To get the result you want you would use:
datetime.datetime.now().strftime('%a, %d %b %Y %H:%M:%S %z')
for the -0700 (timezone offset) part to print anything other than a blank string you need to pass in a timezone aware date (for example US/Arizona in -0700 UTC). To do this (using a third party pytz module, you would do the following) :
import pytz
datetime.datetime.now(tz=pytz.timezone("US/Arizona")).strftime('%a, %d %b %Y %H:%M:%S %z')

Categories

Resources