### Archive

Posts Tagged ‘datetime’

## How old are you in days?

Problem
You want to calculate how old you are in days.

Solution
Let’s use a popular 3rd party date/time library for this purpose called pendulum.

As an example, let’s take Arnold Schwarzenegger, who was born on July 30, 1947. So let’s answer the following question: how old is Schwarzenegger today?

```>>> import pendulum
>>>
>>> born = pendulum.parse("1947-07-30")
>>> born
DateTime(1947, 7, 30, 0, 0, 0, tzinfo=Timezone('UTC'))
>>> today = pendulum.now()
>>> today
DateTime(2018, 8, 14, 21, 32, 33, 248489, tzinfo=Timezone('Europe/Budapest'))
>>>
>>> diff = today - born
>>> diff
<Period [1947-07-30T00:00:00+00:00 -> 2018-08-14T21:32:33.248489+02:00]>
>>>
>>> diff.in_years()
71
>>> diff.in_words()
'71 years 2 weeks 1 day 19 hours 32 minutes 33 seconds'
>>> diff.in_days()
25948
```
Categories: python Tags: ,

## subtract a day from a python date

Problem
When working with dates, I prefer the order yyyy-mm-dd (e.g. 2015-07-10). Its main advantage is that if you use it as a prefix and sort your entries, you get them in chronological order. (Another advantage is that in my home country we use this order, so this is much closer to my thinking).

So, I faced the following problem: having a date as a string (“2015-07-10”), calculate the date one day before and produce a string again (“2015-07-09”).

Solution

```>>> from datetime import datetime, timedelta
>>> date = "2015-07-10"
>>> today = datetime.strptime(date, '%Y-%m-%d')
>>> today
datetime.datetime(2015, 7, 10, 0, 0)
>>> yesterday = today - timedelta(days=1)
>>> yesterday
datetime.datetime(2015, 7, 9, 0, 0)
>>> yesterday.strftime('%Y-%m-%d')
'2015-07-09'
```

Remark
Back to dates: if I need to write a date in English, I write it like this: “May 12, 1984”. Avoid “05-12-1984”, because what is it? May 12? Or December 5? God knows only.

Categories: python Tags: , , , ,

## UTC now → timestamp → UTC time

Problem
Say you have an application and you want to store the date/time of an event. Later you want to see this date/time.

Solution
Take the current UTC date/time and convert it to a timestamp, which is an integer. Store this value. Then read it and convert it back to UTC date/time.

```>>> import datetime
>>>
>>> utcnow = datetime.datetime.utcnow()
>>> utcnow
datetime.datetime(2015, 1, 25, 18, 10, 41, 803198)
>>> ts = int(utcnow.timestamp())
>>> ts
1422205841
>>> datetime.datetime.fromtimestamp(ts)
datetime.datetime(2015, 1, 25, 18, 10, 41)
>>>
```
Categories: python Tags: , , ,

## Convert a date string to a date object

Problem
I have a date string (‘Sat, 29 Oct 2011 18:32:56 GMT’) that I want to convert to a timestamp (‘2011_10_29’). I want to convert ‘Oct’ to ’10’ using the standard library, I don’t want to create a string array for this with the names of the months.

Solution

```>>> from datetime import datetime
>>> s = 'Sat, 29 Oct 2011 18:32:56 GMT'
>>> s.split()[1:4]
['29', 'Oct', '2011']
>>> year, month, day = s.split()[1:4][::-1]
>>> year, month, day
('2011', 'Oct', '29')
>>> if len(day) == 1:
...     day = '0' + day
...
>>> date = datetime.strptime("{yyyy} {Mmm} {dd}".format(yyyy=year, Mmm=month, dd=day), "%Y %b %d")
>>> template = "{year}_{month:02}_{day:02}"
>>> template.format(year=date.year, month=date.month, day=date.day)
'2011_10_29'
```

I used this conversion in this source code.

You can find the list of datetime formatting directives (`%Y`, `%b`, etc.) at the bottom of this page.

Categories: python