Leo Marcinkus
Leo Marcinkus

Reputation: 78

How do I format time in MicroPython?

Using a Raspberry Pi Pico and MicroPython I am trying to convert time.localtime() to a string. I tried .join() but the Raspberry Pi Pico runs MicroPython:

from machine import Pin, I2C
from ssd1306 import SSD1306_I2C

now = time.localtime()
print("Current date and time: ")
print(now)

w = 128
h = 32

i2c = I2C(0, scl=Pin(17), sda=Pin(16), freq=200000)
addr = i2c.scan()[0]
oled = SSD1306_I2C(w, h, i2c, addr)

oled.fill(0)
oled.text("Raspberry Pi ", 5, 5)
olex.text("Hi Leo", 5, 15)

oled.show()

Upvotes: 1

Views: 6235

Answers (2)

Adam
Adam

Reputation: 2361

A small improvement to Lixas' answer. I think the following code will be cleaner:

import time

year, month, day, hour, minute, second, weekday, yearday = time.localtime()

print(f"Date: {day}/{month}/{year}")
print(f"Time: {hour}:{minute}:{second}")

Upvotes: 1

Lixas
Lixas

Reputation: 7308

import time

now = time.localtime()
print("Date: {}/{}/{}".format(now[1], now[2], now[0]))
print("Time: {}:{}".format(now[3], now[4]))

Your variable now has all required data- it consis of tuple

(year, month, mday, hour, minute, second, weekday, yearday)

Documentation available here

Upvotes: 5

Related Questions