Datetime Format and calculation - python

I'm trying to make a simple system which would get the current time and get another time after few secs, then see the difference with both of the times, so it's 2 seconds. So what I need is the other format like this > YEAR,MONTH,DAY HOUR:MIN.
This is the code which I use for this purpose, but in brackets there are just an example of the format I need.
a = datetime.datetime.now( %Y, %m %d %H:%M)
time.sleep(2)
b = datetime.datetime.now( %Y, %m %d %H:%M)
print(b-a)
print(a)
print(b)

I thing strftime is what you're looking for
import datetime
import time
a = datetime.datetime.now()
time.sleep(2)
b = datetime.datetime.now()
print(b-a)
print(a.strftime("%Y, %m, %d %H:%M"))
print(b.strftime("%Y, %m, %d %H:%M"))
prints
0:00:02.001719
2019, 09, 04 15:17
2019, 09, 04 15:17
For more formats, you can see strftime reference: https://www.programiz.com/python-programming/datetime/strftime.

You can convert a datetime.datetime instance to a string formatted to your liking using the strftime() function. For instance, to print with your preferred formatting you could do the following:
>>> import datetime
>>> a = datetime.datetime.now()
>>> print(a.strftime("%Y, %m %d %H:%M")
2019, 09 04 17:11
Subtracting two dates will yield a datetime.timedelta object, you can convert this to the number of seconds using the total_seconds() function:
>>> import datetime
>>> from time import sleep
>>> a = datetime.datetime.now()
>>> sleep(2)
>>> b = datetime.datetime.now()
>>> delta = b - a
>>> print(delta.total_seconds())
2.001301

Related

Extract month from timestamp of a dict using python [duplicate]

I have a date string with the format 'Mon Feb 15 2010'. I want to change the format to '15/02/2010'. How can I do this?
datetime module could help you with that:
datetime.datetime.strptime(date_string, format1).strftime(format2)
For the specific example you could do
>>> import datetime
>>> datetime.datetime.strptime('Mon Feb 15 2010', '%a %b %d %Y').strftime('%d/%m/%Y')
'15/02/2010'
>>>
You can install the dateutil library. Its parse function can figure out what format a string is in without having to specify the format like you do with datetime.strptime.
from dateutil.parser import parse
dt = parse('Mon Feb 15 2010')
print(dt)
# datetime.datetime(2010, 2, 15, 0, 0)
print(dt.strftime('%d/%m/%Y'))
# 15/02/2010
convert string to datetime object
from datetime import datetime
s = "2016-03-26T09:25:55.000Z"
f = "%Y-%m-%dT%H:%M:%S.%fZ"
out = datetime.strptime(s, f)
print(out)
output:
2016-03-26 09:25:55
>>> from_date="Mon Feb 15 2010"
>>> import time
>>> conv=time.strptime(from_date,"%a %b %d %Y")
>>> time.strftime("%d/%m/%Y",conv)
'15/02/2010'
As this question comes often, here is the simple explanation.
datetime or time module has two important functions.
strftime - creates a string representation of date or time from a datetime or time object.
strptime - creates a datetime or time object from a string.
In both cases, we need a formating string. It is the representation that tells how the date or time is formatted in your string.
Now lets assume we have a date object.
>>> from datetime import datetime
>>> d = datetime(2010, 2, 15)
>>> d
datetime.datetime(2010, 2, 15, 0, 0)
If we want to create a string from this date in the format 'Mon Feb 15 2010'
>>> s = d.strftime('%a %b %d %y')
>>> print s
Mon Feb 15 10
Lets assume we want to convert this s again to a datetime object.
>>> new_date = datetime.strptime(s, '%a %b %d %y')
>>> print new_date
2010-02-15 00:00:00
Refer This document all formatting directives regarding datetime.
#codeling and #user1767754 : The following two lines will work. I saw no one posted the complete solution for the example problem that was asked. Hopefully this is enough explanation.
import datetime
x = datetime.datetime.strptime("Mon Feb 15 2010", "%a %b %d %Y").strftime("%d/%m/%Y")
print(x)
Output:
15/02/2010
You may achieve this using pandas as well:
import pandas as pd
pd.to_datetime('Mon Feb 15 2010', format='%a %b %d %Y').strftime('%d/%m/%Y')
Output:
'15/02/2010'
You may apply pandas approach for different datatypes as:
import pandas as pd
import numpy as np
def reformat_date(date_string, old_format, new_format):
return pd.to_datetime(date_string, format=old_format, errors='ignore').strftime(new_format)
date_string = 'Mon Feb 15 2010'
date_list = ['Mon Feb 15 2010', 'Wed Feb 17 2010']
date_array = np.array(date_list)
date_series = pd.Series(date_list)
old_format = '%a %b %d %Y'
new_format = '%d/%m/%Y'
print(reformat_date(date_string, old_format, new_format))
print(reformat_date(date_list, old_format, new_format).values)
print(reformat_date(date_array, old_format, new_format).values)
print(date_series.apply(lambda x: reformat_date(x, old_format, new_format)).values)
Output:
15/02/2010
['15/02/2010' '17/02/2010']
['15/02/2010' '17/02/2010']
['15/02/2010' '17/02/2010']
Just for the sake of completion: when parsing a date using strptime() and the date contains the name of a day, month, etc, be aware that you have to account for the locale.
It's mentioned as a footnote in the docs as well.
As an example:
import locale
print(locale.getlocale())
>> ('nl_BE', 'ISO8859-1')
from datetime import datetime
datetime.strptime('6-Mar-2016', '%d-%b-%Y').strftime('%Y-%m-%d')
>> ValueError: time data '6-Mar-2016' does not match format '%d-%b-%Y'
locale.setlocale(locale.LC_ALL, 'en_US')
datetime.strptime('6-Mar-2016', '%d-%b-%Y').strftime('%Y-%m-%d')
>> '2016-03-06'
use datetime library
http://docs.python.org/library/datetime.html look up 9.1.7.
especiall strptime() strftime() Behavior¶
examples
http://pleac.sourceforge.net/pleac_python/datesandtimes.html
If you dont want to define the input date format then, Install dateparser (pip install dateparser) and,
from dateparser import parse
parse("Mon Feb 15 2010").strftime("%d/%m/%Y")

How i can change date format in python [duplicate]

I have a date string with the format 'Mon Feb 15 2010'. I want to change the format to '15/02/2010'. How can I do this?
datetime module could help you with that:
datetime.datetime.strptime(date_string, format1).strftime(format2)
For the specific example you could do
>>> import datetime
>>> datetime.datetime.strptime('Mon Feb 15 2010', '%a %b %d %Y').strftime('%d/%m/%Y')
'15/02/2010'
>>>
You can install the dateutil library. Its parse function can figure out what format a string is in without having to specify the format like you do with datetime.strptime.
from dateutil.parser import parse
dt = parse('Mon Feb 15 2010')
print(dt)
# datetime.datetime(2010, 2, 15, 0, 0)
print(dt.strftime('%d/%m/%Y'))
# 15/02/2010
convert string to datetime object
from datetime import datetime
s = "2016-03-26T09:25:55.000Z"
f = "%Y-%m-%dT%H:%M:%S.%fZ"
out = datetime.strptime(s, f)
print(out)
output:
2016-03-26 09:25:55
>>> from_date="Mon Feb 15 2010"
>>> import time
>>> conv=time.strptime(from_date,"%a %b %d %Y")
>>> time.strftime("%d/%m/%Y",conv)
'15/02/2010'
As this question comes often, here is the simple explanation.
datetime or time module has two important functions.
strftime - creates a string representation of date or time from a datetime or time object.
strptime - creates a datetime or time object from a string.
In both cases, we need a formating string. It is the representation that tells how the date or time is formatted in your string.
Now lets assume we have a date object.
>>> from datetime import datetime
>>> d = datetime(2010, 2, 15)
>>> d
datetime.datetime(2010, 2, 15, 0, 0)
If we want to create a string from this date in the format 'Mon Feb 15 2010'
>>> s = d.strftime('%a %b %d %y')
>>> print s
Mon Feb 15 10
Lets assume we want to convert this s again to a datetime object.
>>> new_date = datetime.strptime(s, '%a %b %d %y')
>>> print new_date
2010-02-15 00:00:00
Refer This document all formatting directives regarding datetime.
#codeling and #user1767754 : The following two lines will work. I saw no one posted the complete solution for the example problem that was asked. Hopefully this is enough explanation.
import datetime
x = datetime.datetime.strptime("Mon Feb 15 2010", "%a %b %d %Y").strftime("%d/%m/%Y")
print(x)
Output:
15/02/2010
You may achieve this using pandas as well:
import pandas as pd
pd.to_datetime('Mon Feb 15 2010', format='%a %b %d %Y').strftime('%d/%m/%Y')
Output:
'15/02/2010'
You may apply pandas approach for different datatypes as:
import pandas as pd
import numpy as np
def reformat_date(date_string, old_format, new_format):
return pd.to_datetime(date_string, format=old_format, errors='ignore').strftime(new_format)
date_string = 'Mon Feb 15 2010'
date_list = ['Mon Feb 15 2010', 'Wed Feb 17 2010']
date_array = np.array(date_list)
date_series = pd.Series(date_list)
old_format = '%a %b %d %Y'
new_format = '%d/%m/%Y'
print(reformat_date(date_string, old_format, new_format))
print(reformat_date(date_list, old_format, new_format).values)
print(reformat_date(date_array, old_format, new_format).values)
print(date_series.apply(lambda x: reformat_date(x, old_format, new_format)).values)
Output:
15/02/2010
['15/02/2010' '17/02/2010']
['15/02/2010' '17/02/2010']
['15/02/2010' '17/02/2010']
Just for the sake of completion: when parsing a date using strptime() and the date contains the name of a day, month, etc, be aware that you have to account for the locale.
It's mentioned as a footnote in the docs as well.
As an example:
import locale
print(locale.getlocale())
>> ('nl_BE', 'ISO8859-1')
from datetime import datetime
datetime.strptime('6-Mar-2016', '%d-%b-%Y').strftime('%Y-%m-%d')
>> ValueError: time data '6-Mar-2016' does not match format '%d-%b-%Y'
locale.setlocale(locale.LC_ALL, 'en_US')
datetime.strptime('6-Mar-2016', '%d-%b-%Y').strftime('%Y-%m-%d')
>> '2016-03-06'
use datetime library
http://docs.python.org/library/datetime.html look up 9.1.7.
especiall strptime() strftime() Behavior¶
examples
http://pleac.sourceforge.net/pleac_python/datesandtimes.html
If you dont want to define the input date format then, Install dateparser (pip install dateparser) and,
from dateparser import parse
parse("Mon Feb 15 2010").strftime("%d/%m/%Y")

How to extract second from date and time in python

By using:
import os,os.path,time,shutil,datetime
print time.ctime(os.path.getmtime("/home/sulata/Documents/source/"))
print time.ctime(os.path.getmtime("/home/sulata/Documents/destination/"))
I'm getting the outputs:
Mon Apr 2 15:56:00 2018
Mon Apr 2 15:56:03 2018
I want to get the time without seconds.
The general method is:
import time
time.strftime(format)
example:
>>>time.strftime("%H:%M:%S")
20:08:40
In your case:
>>> time.strftime("%H:%M")
13:41
>>>time.strftime("%a %b %d %H:%M %Y")
'Mon Apr 02 13:27 2018'
if you want to remove the Zero, you could do something like this...
>>> time.strftime("%a %b "+str(int(time.strftime("%d"))) +" %H:%M %Y")
'Mon Apr 2 13:33 2018'
Use datetime to get the seconds.
Ex:
import os,os.path,time,shutil,datetime
print datetime.datetime.strptime(time.ctime(os.path.getmtime(r"/home/sulata/Documents/source/")), "%a %b %d %H:%M:%S %Y").second
JulioCamPlaz has already provided a decent enough solution, but if you want to maintain the date format, you can use regex for this:
import re
x = time.ctime(os.path.getmtime("/home/sulata/Documents/source/"))
print(re.sub(r':\d{1,2}\s', ' ', x))
What this does is that it removes the final two digits (seconds) of the time which are followed by a space, and replaces it with a space.
Although this may be an over-complicated method, it is short, and gives you the exact same date format without the seconds, and without altering it in any way.
getmtime returns a timestamp, so you can format it using strftime to whatever format you need:
>>> import datetime as dt
>>> import os
>>> mTime = os.path.getmtime("/tmp/xauth-1000-_0")
>>> dt.datetime.fromtimestamp(mTime).strftime("%Y-%m-%d %H:%M")
'2018-04-01 22:07'
Format identifiers can be found in the docs.
You can try this -
>>> import time, os
>>>
>>> x = time.gmtime(os.path.getmtime('/home/abhi/test.file'))
>>>
>>> x
time.struct_time(tm_year=2018, tm_mon=4, tm_mday=2, tm_hour=11, tm_min=19, tm_sec=43, tm_wday=0, tm_yday=92, tm_isdst=0)
>>> x.tm_sec
43
>>> x.tm_hour
11
>>>

How do I retrieve all RSS entries that are no more than X days old

I am using Python and the RSS feedparser module to retrieve RSS entries. However I only want to retrieve a news item if it is no more than x days old.
For example if x=4 then my Python code should not fetch anything four days older than the current date.
Feedparser allows you to scrape the 'published' date for the entry, however it is of type unicode and I don't know how to convert this into a datetime object.
Here is some example input:
date = 'Thu, 29 May 2014 20:39:20 +0000'
Here is what I have tried:
from datetime import datetime
date_object = datetime.strptime(date, '%a, %d %b %Y %H:%M:%S %z')
This is the error I get:
ValueError: 'z' is a bad directive in format '%a, %d %b %Y %H:%M:%S %z'
This is what I hope to do with it:
from datetime import datetime
a = datetime(today)
b = datetime(RSS_feed_entry_date)
>>> a-b
datetime.timedelta(6, 1)
(a-b).days
6
For this, you already have a time.struct_time look at feed.entries[0].published_parsed
you can use time.mktime to convert this to a timestamp and compare it with time.time() to see how far in the past it is:
An example:
>>> import feedparser
>>> import time
>>> f = feedparser.parse("http://feeds.bbci.co.uk/news/rss.xml")
>>> f.entries[0].published_parsed
time.struct_time(tm_year=2014, tm_mon=5, tm_mday=30, tm_hour=14, tm_min=6, tm_sec=8, tm_wday=4, tm_yday=150, tm_isdst=0)
>>> time.time() - time.mktime(feed.entries[0].published_parsed)
4985.511506080627
obviosuly this will be a different value for you, but if this is less than (in your case) 86400 * 4 (number of seconds in 4 days), it's what you want.
So, concisely
[entry for entry in f.entries if time.time() - time.mktime(entry.published_parsed) < (86400*4)]
would give you your list
from datetime import datetime
date = 'Thu, 29 May 2014 20:39:20 +0000'
if '+' in date:
dateSplit = date.split('+')
offset = '+' + dateSplit[1]
restOfDate = str(dateSplit[0])
date_object = datetime.strptime(restOfDate + ' ' + offset, '%a, %d %b %Y %H:%M:%S ' + offset)
print date_object
Yields 2014-05-29 20:39:20, as I was researching your timezone error I came across this other SO question that says that strptime has trouble with time zones (link to question).

Parse date string and change format

I have a date string with the format 'Mon Feb 15 2010'. I want to change the format to '15/02/2010'. How can I do this?
datetime module could help you with that:
datetime.datetime.strptime(date_string, format1).strftime(format2)
For the specific example you could do
>>> import datetime
>>> datetime.datetime.strptime('Mon Feb 15 2010', '%a %b %d %Y').strftime('%d/%m/%Y')
'15/02/2010'
>>>
You can install the dateutil library. Its parse function can figure out what format a string is in without having to specify the format like you do with datetime.strptime.
from dateutil.parser import parse
dt = parse('Mon Feb 15 2010')
print(dt)
# datetime.datetime(2010, 2, 15, 0, 0)
print(dt.strftime('%d/%m/%Y'))
# 15/02/2010
convert string to datetime object
from datetime import datetime
s = "2016-03-26T09:25:55.000Z"
f = "%Y-%m-%dT%H:%M:%S.%fZ"
out = datetime.strptime(s, f)
print(out)
output:
2016-03-26 09:25:55
>>> from_date="Mon Feb 15 2010"
>>> import time
>>> conv=time.strptime(from_date,"%a %b %d %Y")
>>> time.strftime("%d/%m/%Y",conv)
'15/02/2010'
As this question comes often, here is the simple explanation.
datetime or time module has two important functions.
strftime - creates a string representation of date or time from a datetime or time object.
strptime - creates a datetime or time object from a string.
In both cases, we need a formating string. It is the representation that tells how the date or time is formatted in your string.
Now lets assume we have a date object.
>>> from datetime import datetime
>>> d = datetime(2010, 2, 15)
>>> d
datetime.datetime(2010, 2, 15, 0, 0)
If we want to create a string from this date in the format 'Mon Feb 15 2010'
>>> s = d.strftime('%a %b %d %y')
>>> print s
Mon Feb 15 10
Lets assume we want to convert this s again to a datetime object.
>>> new_date = datetime.strptime(s, '%a %b %d %y')
>>> print new_date
2010-02-15 00:00:00
Refer This document all formatting directives regarding datetime.
#codeling and #user1767754 : The following two lines will work. I saw no one posted the complete solution for the example problem that was asked. Hopefully this is enough explanation.
import datetime
x = datetime.datetime.strptime("Mon Feb 15 2010", "%a %b %d %Y").strftime("%d/%m/%Y")
print(x)
Output:
15/02/2010
You may achieve this using pandas as well:
import pandas as pd
pd.to_datetime('Mon Feb 15 2010', format='%a %b %d %Y').strftime('%d/%m/%Y')
Output:
'15/02/2010'
You may apply pandas approach for different datatypes as:
import pandas as pd
import numpy as np
def reformat_date(date_string, old_format, new_format):
return pd.to_datetime(date_string, format=old_format, errors='ignore').strftime(new_format)
date_string = 'Mon Feb 15 2010'
date_list = ['Mon Feb 15 2010', 'Wed Feb 17 2010']
date_array = np.array(date_list)
date_series = pd.Series(date_list)
old_format = '%a %b %d %Y'
new_format = '%d/%m/%Y'
print(reformat_date(date_string, old_format, new_format))
print(reformat_date(date_list, old_format, new_format).values)
print(reformat_date(date_array, old_format, new_format).values)
print(date_series.apply(lambda x: reformat_date(x, old_format, new_format)).values)
Output:
15/02/2010
['15/02/2010' '17/02/2010']
['15/02/2010' '17/02/2010']
['15/02/2010' '17/02/2010']
Just for the sake of completion: when parsing a date using strptime() and the date contains the name of a day, month, etc, be aware that you have to account for the locale.
It's mentioned as a footnote in the docs as well.
As an example:
import locale
print(locale.getlocale())
>> ('nl_BE', 'ISO8859-1')
from datetime import datetime
datetime.strptime('6-Mar-2016', '%d-%b-%Y').strftime('%Y-%m-%d')
>> ValueError: time data '6-Mar-2016' does not match format '%d-%b-%Y'
locale.setlocale(locale.LC_ALL, 'en_US')
datetime.strptime('6-Mar-2016', '%d-%b-%Y').strftime('%Y-%m-%d')
>> '2016-03-06'
use datetime library
http://docs.python.org/library/datetime.html look up 9.1.7.
especiall strptime() strftime() Behavior¶
examples
http://pleac.sourceforge.net/pleac_python/datesandtimes.html
If you dont want to define the input date format then, Install dateparser (pip install dateparser) and,
from dateparser import parse
parse("Mon Feb 15 2010").strftime("%d/%m/%Y")

Categories